7

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

Richard
  • 4,516
  • 11
  • 60
  • 87
  • 1
    Do you process the return value of `json_decode` in any way? – Gumbo Feb 10 '10 at 14:53
  • thanks, I try to use it like an associative array afterwards. I am now storing the post array in a session variable so I can do a print_r or var_dump somewhere else. Now I can't see anything. – Richard Feb 10 '10 at 15:04

8 Answers8

6

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
Clark Burns
  • 71
  • 1
  • 3
6

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 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 Feb 10 '10 at 15:14
  • It seems you are right and Saffraz. I will look into serialize then. – Richard Feb 10 '10 at 16:02
5

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 ) ) 
Shinto Anto
  • 66
  • 1
  • 2
4

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
  • 377,238
  • 77
  • 533
  • 578
1

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.

0

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
  • 6,694
  • 4
  • 28
  • 36
  • the posted string is in json format with brackets like these{}, I think there must be some parsing involved here. – Richard Feb 10 '10 at 15:07
0

Maybe it will help those who are looking :)

You send data like this:

$.ajax({
    url: 'url_name',
    data: {
        form_data: $('#form').serialize(),

    },
    dataType: 'json',
    method: 'POST'
})

console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'

Then on the server side use parse_str( $_POST['form_data'], $res).

Then the variable $res will contain the following:

Array
( 
    [f_ctrType] => 5
    [f_status] => 2
    [f_createdAt] => '2022/02/24'
    [f_participants] => 1700
)
-1

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;
    }
?>