1

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).

Wanceslas
  • 107
  • 1
  • 1
  • 10

3 Answers3

1

I would suggest the following structure on the data which you pass:

Javascript:

var DTO = { 
    type: [1,2,3],
    vars: {  
        name: 'foo',
        email: 'foo@bar.com'
    }
};

var stringifiedData = JSON.stringify(DTO); 

// will result in:
//{"type":[1,2,3],"vars":{"name":"foo","email":"foo@bar.com"}} 

$.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

Johan
  • 35,120
  • 54
  • 178
  • 293
  • Thanks, I did like you. I built an object instead of an array and I've used `JSON.stringify` and in my php I've used `json_decode`. Everything is working perfectly, Tanks alot. – Wanceslas May 09 '13 at 20:58
  • +1 for the sample and the detail on both sides . . . would have been perfect if it explained why the previous method wasn't working . . . – ernie May 09 '13 at 21:03
0

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);});
Wurstbro
  • 974
  • 1
  • 9
  • 21
0

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.

Community
  • 1
  • 1
ernie
  • 6,356
  • 23
  • 28