Reputation: 137
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).
Upvotes: 1
Views: 130
Reputation: 35213
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: Mon, 26 Jul 1997 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.
http://php.net/manual/en/function.json-decode.php
Upvotes: 1
Reputation: 6356
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.
Upvotes: 0
Reputation: 974
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);});
Upvotes: 0