Richard
Richard

Reputation: 4546

How to get the POST values from serializeArray?

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

Upvotes: 8

Views: 53879

Answers (9)

M-A-X
M-A-X

Reputation: 492

Improved solution of @Adriano de Abreu Wanderley to handle with field names with no key in []

    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:
                        if($d["name"][1] === '') {
                            $a[$d["name"][0]][] = $d["value"];
                        } else {
                            $a[$d["name"][0]][$d["name"][1]] = $d["value"];
                        }
                    break;

                    case 3:
                        if($d["name"][2] === '') {
                            $a[$d["name"][0]][$d["name"][1]][] = $d["value"];
                        } else {
                            $a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
                        }
                    break;

                    case 4:
                        if($d["name"][3] === '') {
                            $a[$d["name"][0]][$d["name"][1]][$d["name"][2]][] = $d["value"];
                        } else {
                            $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;
    }

    // example of usage
    if(!empty($_POST['data']))
    {
        $arData = serializeToArray(json_decode($_POST['data'], 1));
    }

Upvotes: 0

Yuriy Klosov
Yuriy Klosov

Reputation: 1

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
)

Upvotes: 0

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

Upvotes: 0

Shinto Anto
Shinto Anto

Reputation: 64

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] => [email protected] ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) ) 

Upvotes: 4

Seymore Throttle
Seymore Throttle

Reputation: 69

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.

Upvotes: 0

Clark Burns
Clark Burns

Reputation: 69

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

Upvotes: 5

Gordon
Gordon

Reputation: 316939

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.

Upvotes: 6

Sarfraz
Sarfraz

Reputation: 382626

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

Upvotes: 3

Ty W
Ty W

Reputation: 6814

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.

Upvotes: 0

Related Questions