I'm trying to send an array from JavaScript to PHP with the $.post() method of Jquery.
I've tried jQuery.serialize(), jQuery.serializeArray(), JSON.stringify() and all of them didn't work.
Here is my code:
$.post("ajax/"+action+"_xml.php",{'array': array},function(data){console.log(data);});
the array looks like this :
array["type"]
array["vars"]["name"]
array["vars"]["email"]
array["vars"] has more than 2 elements.
The result in my php $_POST variable is an empty array (length 0).
3 Answers 3
I would suggest the following structure on the data which you pass:
Javascript:
var DTO = {
type: [1,2,3],
vars: {
name: 'foo',
email: '[email protected]'
}
};
var stringifiedData = JSON.stringify(DTO);
// will result in:
//{"type":[1,2,3],"vars":{"name":"foo","email":"[email protected]"}}
$.post("ajax/"+action+"_xml.php",{'DTO': stringifiedData },function(data){
console.log(data);
});
PHP:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 1997年7月26日 05:00:00 GMT');
header('Content-type: application/json');
$DTO = $_POST['DTO'];
if(isset($DTO))
{
$assocResult = json_decode($DTO, true);
var_dump($assocResult); //do stuff with $assocResult here
}
Passing true as the second argument to json_decode will make it return an associative array.
2 Comments
JSON.stringify and in my php I've used json_decode. Everything is working perfectly, Tanks alot.I'm not sure whether you can post an array like that.
Splitting it should work just fine:
$.post("ajax/"+action+"_xml.php",{'type': array["type"], 'name' : array["vars"]["name"],...},function(data){console.log(data);});
1 Comment
You need to turn your javascript array into a string, as that's all the post() method accepts. Most people do this by converting their array to JSON.