Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:

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

// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array

its possible by using the serialize array and json_decode()

// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call

//PHP
 $value =  (json_decode(stripslashes($_REQUEST['values']), true));

the values are received as an array

each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']

print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test@gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) ) 

I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.

// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...

// PHP
echo $_POST['fieldName'];

This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.

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.

You can use this function in php to reverse serializeArray().

<?php
function serializeToArray($data){
        foreach ($data as $d) {
            if( substr($d["name"], -1) == "]" ){
                $d["name"] = explode("[", str_replace("]", "", $d["name"]));
                switch (sizeof($d["name"])) {
                    case 2:
                        $a[$d["name"][0]][$d["name"][1]] = $d["value"];
                    break;

                    case 3:
                        $a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
                    break;

                    case 4:
                        $a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
                    break;
                }
            }else{
                $a[$d["name"]] = $d["value"];
            } // if
        } // foreach

        return $a;
    }
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top