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

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
+1 for the sample and the detail on both sides . . . would have been perfect if it explained why the previous method wasn't working . . .
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);});

1 Comment

This way might not be the best considering an array with dozens of keys. (possibility)
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.

1 Comment

Since there is nothing wrong with your answer, here's an upvote to nullify it ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.