Cant access the serialized data from AJAX inside an PHP file - ajax

Trying to get the send data inside an Wordpress plugin but I cant get the data to work. So how do I get the data from the serialized part inside a php file?
// the code
<form method="post" id="form-settings" action="ajaxpro.php" >
<?php wp_nonce_field( 'settings', 'settings_nonce', false );?>
<input name="field-one" type="text"/>
<input name="field-two" type="text"/>
<textarea name="field_three">Hello world</textarea>
// notice the double fields
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<button id="submitme" name="save-form">Save</button>
</form>
$('body').on('submit', '#form-settings', function(e){
var seri =$(this).serializeArray()
$.post(ajaxurl, {
action: 'save_ajax_func',
posted: seri
}, function(response) {
console.log( response );
});
return false;
});
//notice that I do use double field names(field-x)
echo $_POST[ 'posted' ][ 'field-one' ] // not working

To use the [] notation in the html it would be posted[field-x]
<input name="posted[field-x]" type="text"/>
the ajax will have to change to below
var seri = $(this).serializeArray();
seri.push({name:'action',value:'save_ajax_func'});
$.post(ajaxurl, seri, function(response) {
console.log( response );
});

Related

Stuck on uploading image by formData

I have a page that user can change his picture profile, but I'm stuck when I do a submitHandle, because when I try to console.log(formData) it always gives me empty results.
this is my input file of picture profile
<input id="file-upload" type="file" name="fileUpload" class="d-none" #change="fileUpload">
<label for="file-upload">
<img class="ap-img__main rounded-circle wh-120 bg-lighter d-flex" :src="`/dashboard/img/author/profile/`+user.avatar"alt="profile img" v-if="!imagePreview">
<img class="ap-img__main rounded-circle wh-120 bg-lighter d-flex" :src="imagePreview" alt="profile img" v-if="imagePreview">
<span class="cross" id="remove_pro_pic">
<i class="fas fa-camera"></i>
</span>
</label>
this is the methods
fileUpload(e) {
let selectedImage = e.target.files[0];
this.imageLocation = selectedImage;
console.log(this.imageLocation.name);
let reader = new FileReader();
reader.readAsDataURL(this.imageLocation)
reader.onload = e => {
this.imagePreview = e.target.result;
}
},
and it has results like this,
But when I click the save button to save file, by formData method, it will have empty results.
This is the button update,
<div class="button-group d-flex pt-25 justify-content-start">
<button #click="submitHandle" class="btn btn-primary btn-default btn-squared text capitalize radius-md shadow2">Update details
</button>
</div>
this is the submitHandle methods,
submitHandle() {
e.preventDefault();
var formData = new FormData();
formData.append('image', this.imageLocation);
formData.append('name', this.user.name);
formData.append('username', this.user.username);
formData.append('email', this.user.email);
formData.append('phone', this.user.phone);
formData.append('gender', this.user.gender);
formData.append('birth', this.user.birth);
formData.append('bio', this.user.bio);
formData.append("facebook", this.user.facebook);
formData.append("instagram", this.user.instagram);
console.log(formData);
},
and when on console log,
it is just shown like this,
please anyone, can help me to solve this?
Thank you very much.
Logging FormData
The default toString() of FormData does not log its entries, so it only seems like the FormData is empty.
A quick way to log the entries is to wrap FormData.prototype.entries in an array:
console.log(Array.from(formData.entries()))
const formData = new FormData();
formData.append('image', 'my image');
formData.append('name', 'my name');
formData.append('username', 'my username');
formData.append('email', 'my email');
formData.append('phone', 'my phone');
formData.append('gender', 'my gender');
formData.append('birth', 'my birth');
formData.append('bio', 'my bio');
formData.append("facebook", 'my facebook');
formData.append("instagram", 'my instagram');
console.log(Array.from(formData.entries()));
Sending FormData with axios
axios.patch takes the FormData instance as its second argument:
axios.patch(apiServerUrl, formData)
Note you can easily create the FormData from the given <form> element if all its <input>s have the appropriate name attribute set, as seen in this example:
<template>
<form #submit.prevent="submitHandle">
<label>Profile Image <input type="file" name="image" autocomplete="photo" v-model="imageLocation"></label>
<label>Username <input type="text" name="username" autocomplete="username" v-model="user.username"></label>
<label>Email <input type="email" name="email" autocomplete="email" v-model="user.email"></label>
<label>Phone <input type="tel" name="phone" autocomplete="tel" v-model="user.phone"></label>
<label>Gender <input type="text" name="gender" autocomplete="sex" v-model="user.gender"></label>
<label>Birthdate <input type="date" name="birth" autocomplete="bday" v-model="user.birth"></label>
<label>Bio <textarea type="text" name="bio" v-model="user.bio"></textarea></label>
<label>Facebook <input type="text" name="facebook" v-model="user.facebook"></label>
<label>Instagram <input type="text" name="instagram" v-model="user.instagram"></label>
<button type="submit">Submit</button>
</form>
<pre>{{ response }}</pre>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
response: null,
imageLocation: null,
user: {
username: null,
email: null,
phone: null,
gender: null,
birth: null,
bio: null,
facebook: null,
instagram: null,
}
}
},
methods: {
submitHandle(e) {
const form = e.target
const formData = new FormData(form)
axios.patch('https://httpbin.org/patch', formData)
.then(resp => this.response = resp.data)
}
}
}
</script>
<style>
label {
display: block;
}
</style>
demo

How to include new component in axios response

I have an component with text input. After fill input and submit form i sand axios query and after response i need stay on the same page with error popup or include new component with response data.
my component
<template>
<div class="col-md-12">
<div class="form-container">
<form v-on:submit="prepareCollage()" class="main-form">
<div class="form-group">
<input type="hidden" name="_token" value="">
<input placeholder="your text" v-model="text" name="query" type="text" class="form-control">
</div>
<button class="go btn btn-primary">Go!</button>
</form>
</div>
</div>
</template>
<script>
export default {
data () {
return {
text : '',
}
},
methods: {
prepareCollage(){
event.preventDefault();
axios.get('/api/prepare?query='+encodeURIComponent(this.text))
.then(function(result){
const result_data = result.data;
// if controller gave an error
if(result_data.error === true){
let error_text = result_data.error_text;
if(typeof(result_data.with_link) != 'undefined' && result_data.with_link.length > 0){
error_text += "<a href='"+result_data.with_link+"'>"+result_data.link_text+"</a>";
}
Vue.swal({
title: 'Error!',
html: error_text,
type: 'error',
})
}else{
// here i need include new component
}
});
}
}
}
</script>
in "else" block i have to include new vue component with data from this component. I have never used vuejs and have difficulty with understand this.

How to send input hidden in React JS?

I have this form, and I would like to send these values. I know we have to use setState() to store data but how does it work for input type="hidden"?
First question: How to store input hidden to setState ?
Second question: How to serialize data like form.serialize() ?
Third question: How to send these serialize values? Ajax or Axios, who is the better?
Here is the code:
handleSubmit(e) {
e.preventDefault();
/**
$.ajax({
url: "post.php",
type: "POST",
data: DATA,
success:function(data) {
}
});
**/
}
<form onSubmit={this.handleSubmit}>
<input type="hidden" name="action" value="login" />
<input type="email" name="email_user" placeholder="Email" />
<input type="password" name="password_user" placeholder="Mot de passe" />
<button type="submit">Login</button>
</form>
The answer is complex for all your questions.
First of all, it depends on the task: if you just want to send asynchonous request to server on form submit, you don't need to use Component state. Here is a link to the relevant section of the documentation. And use refs to access inputs data.
class FormComponent extends React.Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
// Send your ajax query via jQuery or Axios (I prefer Axios)
axios.get('your_url', {
params: {
action: this.actionInput.value,
email: this.emailInput.value,
password: this.passwordInput.value,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="hidden" name="action" value="login"
ref={(input) => { this.actionInput = input }} />
<input type="email" name="email_user" placeholder="Email"
ref={(input) => { this.emailInput = input }}/>
<input type="password" name="password_user" placeholder="Mot de passe"
ref={(input) => { this.passwordInput = input }}/>
<button type="submit">Login</button>
</form>
);
}
}
All data can be stored on React's state, but if you still need to have inputs on your form you can do something like this:
const handleSubmit = e => {
e.preventDefault();
const inputs = Object.values(e.target)
.filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
setFormVals({ ...formVals, ...inputs });
}
See the demo below:
const Demo = () => {
const [formValues] = React.useState({});
const handleSubmit = e => {
e.preventDefault();
const inputs = Object.values(e.target)
.filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
console.log(inputs);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" value={formValues.name} />
<input name="email" placeholder="Email" value={formValues.email} />
<input name="hiddenInput" value="hiddenValue" type="hidden" />
<button type="submit">Submit</button>
</form>
);
}
ReactDOM.render(<Demo />, document.getElementById('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
If you know what the inputs that you need you can do something like this:
const Demo = () => {
const formRef = React.useRef(null);
const [formValues, setFormValues] = React.useState({});
const handleChange = e => {
setFormValues({
...formValues,
[e.target.name]: e.target.value,
});
}
const handleSubmit = e => {
e.preventDefault();
setFormValues({ ...formValues, hiddenInput: formRef.current.hiddenInput.value });
}
return (
<form onSubmit={handleSubmit} ref={formRef}>
<input name="name" placeholder="Name" value={formValues.name} onChange={handleChange} />
<input name="email" placeholder="Email" value={formValues.email} onChange={handleChange} />
<input name="hiddenInput" value="hiddenValue" type="hidden" />
<button type="submit">Submit</button>
<pre>{JSON.stringify(formValues, null, 2)}</pre>
</form>
);
}
ReactDOM.render(<Demo />, document.getElementById('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
Answering your questions:
Since you know how to use component's state you may set the value as : <input type='text' value={this.state.foo} /> or even via props passing <input type='hidden' value={this.props.foo} />
You don't need to serialise anything at all. Use your component's local state or even a state container like Redux or Flux in order to pick the appropriate data. Take a look at this fairly simple example:
var SuperForm = React.createClass({
getInitialState() {
return {
name: 'foo',
email: 'baz#example.com'
};
},
submit(e){
e.preventDefault();
console.log("send via AJAX", this.state)
},
change(e,key){
const newState = {};
newState[key] = e.currentTarget.value;
this.setState(newState)
},
render: function() {
return (
<div>
<label>Name</label>
<input
onChange={(e) => this.change(e,'name')}
type="text"
value={this.state.name} />
<label>Email</label>
<input
onChange={(e) => this.change(e,'email')}
type="text"
value={this.state.email} />
<button onClick={this.submit}>Submit</button>
</div>
);
}});
Demo
AJAX is a set of web development techniques while Axios is a JavaScript framework. You may use jQuery, Axios or even vanilla JavaScript.

Passing checkbox value in ajax

Please, I need help in passing the check box value through ajax to other php file
This is my form :
<form class="form-horizontal" onsubmit="Javascript:return validate();" method="post" id="form">
<b>Jawwal Number</b>
<input name="msisdn" type="text" id="msisdn" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Username</b>
<input name="username" type="text" id="username" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Add Extra Security (Activation Code)</b>
<input type="checkbox" name="security" id="security">
<input type="submit" value="submit" class="btn btn-primary">
</form>
And this is my Ajax code :
$("#form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* set all the vars you want to post on here */
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
**'security':$('input[name="security"]').val(),**
'submit': $('input[name="submit"]').val()
};
$.ajax({
url: '/bulk2/admin/process/add_user.php',
method:'POST',
data: parameters,
success: function(msg) {
$('#test').append(msg);
}
})
});
What should I do so that I can pass the checkbox value to the other page ?
You can also use checkbox checked method.
var security = $('input[name="security"]').prop('checked'); /* it will return true or false */
and update your code
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
'security':security,
'submit': $('input[name="submit"]').val()
};
Use the method is() with property :checked.
var parameters = {
'security':$('input[name="security"]').is(':checked'),
};
This works for me.

Ajax call back: Return variable as input value

After ajax call back I need to echo out a variable as value of hidden field.
HTML
<form ajax1>
<input name="Place" value="Milan">
<input name=submit onclick="return submitForm1()">
</form>
<form ajax2>
<input type="hidden" value="$place">
<input name="filter">
<input name=submit onclick="return submitForm2()">
</form>
<div id="result"></div>
Ajax Call
function submitForm1() {
var form1 = document.myform1;
var dataString1 = $(form2).serialize();
$.ajax({
type:'GET',
url:'query.php',
cache: false,
data: dataString1,
success: function(data){
$('#results').html(data);
}
});
return false;
}
PHP
<?
$place= $_GET['Place']
//do stuffs
?>
It works perfectly, but now I need to add a function to echo out $place in value=" " of form ajax2
Any help appreciated

Resources