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
Phil :
You'll need to url-encode the JSON string to make it compatible with the application/x-www-form-urlencoded request you're sending.\nFortunately, jQuery is able to do this for you if you pass it an object of data values.\nconst name = "John";\nconst age = 21;\nconst gender = "m";\nconst subject = ["math", "geograph"];\n\n$.ajax({\n url: `${baseUrl}/student`,\n method: "POST",\n dataType: "json",\n data: {\n name,\n age,\n gender,\n subject: JSON.stringify(subject),\n }\n})\n\nThis will produce the following request body\nname=John&age=21&gender=m&subject=%5B%22math%22%2C%22geograph%22%5D\n\nOn the PHP side you can continue to use...\n$subject = json_decode($_POST['subject'], true);\n\n\nAs 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 to\n$subject = $_POST['subject']; // will be an array\n",
2022-10-21T02:31:06
flyingfox :
The result of JSON.stringify(subject) is still an array\n\r\n\r\nvar subject = [\"math\",\"geograph\"];\nconsole.log(JSON.stringify(subject )); ",
2022-10-21T02:31:12