My current project is passing multiple values to php via ajax and I want to add an array together but I failed to do so.
current JS file:
var name= 'John';
var age= 21;
var gender = 'm';
var postData = 'name='+name+'&age='+age+'&gender=gender';
$.ajax({
type:'POST',
dataType:'json',
url:baseUrl+'/student',
data:postData,
}).done(function (data){
alert('success');
}
});
What I want to add:
var subject = ["math","geograph"];
JSON.stringify(subject ); //to encode the array
I have tried:
var postData = 'name='+name+'&age='+age+'&gender='+gender+'&subject='subject';
and
data:{subject : subject , postData : postData},
and I get this array in php:
$subject = json_decode($request['subject']),true);
But I can’t get the array in my php. How can I solve this problem? Thanks
3
Answers
You’ll need to url-encode the JSON string to make it compatible with the
application/x-www-form-urlencoded
request you’re sending.Fortunately, jQuery is able to do this for you if you pass it an object of data values.
This will produce the following request body
On the PHP side you can continue to use…
As indicated in the comments below, you can also skip the JSON encoding in which case jQuery will send multiple fields named
subject[]
so your PHP would have to change toThe result of
JSON.stringify(subject)
is still an arrayBesides Phil’s answer, one option is to using
join()
to do itWhat you need to do is converting the data from object to string by using the
JSON.stringify
like:then use json_decode in php.