Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the POST values from serializeArray in PHP?

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

like image 580
Richard Avatar asked Feb 10 '10 14:02

Richard


1 Answers

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 https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.

like image 106
Gordon Avatar answered Oct 06 '22 22:10

Gordon