views:

433

answers:

3

Hi,

I am trying this new method I've seen serializeArray().

//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc

So I get these key value pairs, but how do I access them with PHP?

I thought I needed to do this, but it won't work:

// in PHP script
$data = json_decode($_POST['data'], true);

var_dump($data);// will return NULL?

Thanks, Richard

A: 

the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']

edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.

Ty W
the posted string is in json format with brackets like these{}, I think there must be some parsing involved here.
Richard
if I use json_decode, the return value is NULL.
Richard
+2  A: 

The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:

http://www.tutorialspoint.com/jquery/ajax-serializearray.htm

Sarfraz
really, there is no way for php to process it??
Richard
@Richard: it is possible, but you will have find a way around it.
Sarfraz
+1  A: 

Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try

$data = json_decode($_POST['data'], true);
var_dump($data);

If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.

EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use http://www.json.org/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.

Gordon
First I did print_r($_POST) and I saw [object object] and after json_decode the postvar that holds the json data I got nothing. I am now doing var_dump.
Richard
It seems you are right and Saffraz. I will look into serialize then.
Richard