[php] How do I PHP-unserialize a jQuery-serialized form?

Using $('#form').serialize(), I was able to send this over to a PHP page. Now how do I unserialize it in PHP? It was serialized in jQuery.

This question is related to php jquery serialization

The answer is


Provided that your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):

"param1=someVal&param2=someOtherVal"

...something like this is probably all you need:

$params = array();
parse_str($_GET, $params);

$params should then be an array modeled how you would expect. Note this works also with HTML arrays.

See the following for more information: http://www.php.net/manual/en/function.parse-str.php


This is in reply to user1256561. Thanks for your idea.. however i have not taken care of the url decode stuff mentioned in step3.

so here is the php code that will decode the serialized form data, if anyone else needs it. By the way, use this code at your own discretion.

function xyz($strfromAjaxPOST)
{
    $array = "";
    $returndata = "";
    $strArray = explode("&", $strfromPOST);
    $i = 0;
    foreach ($strArray as $str)
    {
        $array = explode("=", $str);
        $returndata[$i] = $array[0];
        $i = $i + 1;
        $returndata[$i] = $array[1];
        $i = $i + 1;
    }
    print_r($returndata);
}

The url post data input will be like: attribute1=value1&attribute2=value2&attribute3=value3 and so on

Output of above code will still be in an array and you can modify it to get it assigned to any variable you want and it depends on how you want to use this data further.

Array
(
    [0] => attribute1
    [1] => value1
    [2] => attribute2
    [3] => value2
    [4] => attribute3
    [5] => value3
)

parse_str($_POST['whatever'], $searcharray);

You can use this function:

function post_unserialize( $key ){
  $post_data = array();
  $post_data = $_POST[ $key ];
  unset($_POST[ $key ]);
  parse_str($post_data, $post_data);
  $_POST = array_merge($_POST, $post_data);
}

How to use it

$_POST['serialized_data'] = 'var1=1&var2=2&var3=3';
post_unserialize( 'serialized_data' );

Simply do this

$get = explode('&', $_POST['seri']); // explode with and

foreach ($get as $key => $value) {
    $need[substr($value, 0 , strpos($value, '='))] =  substr(
        $value, 
        strpos( $value, '=' ) + 1 
    );
}

// access your query param name=ddd&email=aaaaa&username=wwwww&password=wwww&password=eeee
var_dump($need['name']);

In HTML page:

<script>
function insert_tag()
{
    $.ajax({
        url: "aaa.php",
        type: "POST",
        data: {
            ssd: "yes",
            data: $("#form_insert").serialize()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            $("#result1").html(jsonStr['back_message']);
        }
    });
}
</script>

<form id="form_insert">
    <input type="text" name="f1" value="a"/>
    <input type="text" name="f2" value="b"/>
    <input type="text" name="f3" value="c"/>
    <input type="text" name="f4" value="d"/>
    <div onclick="insert_tag();"><b>OK</b></div>
    <div id="result1">...</div>
</form>

on PHP page:

<?php
if(isset($_POST['data']))
{
    parse_str($_POST['data'], $searcharray);
    $data = array(
        "back_message"   => $searcharray['f1']
    );
    echo json_encode($data);
}
?>

on this php code, return f1 field.


Use:

$( '#form' ).serializeArray();

Php get array, dont need unserialize ;)


Why don't use associative array, so you can use it easily

function unserializeForm($str) {
    $returndata = array();
    $strArray = explode("&", $str);
    $i = 0;
    foreach ($strArray as $item) {
        $array = explode("=", $item);
        $returndata[$array[0]] = $array[1];
    }

    return $returndata;
}

Regards


I think you need to separate the form names from its values, one method to do this is to explode (&) so that you will get attribute=value,attribute2=value.

My point here is that you will convert the serialized jQuery string into arrays in PHP.

Here is the steps that you should follow to be more specific.

  1. Passed on the serialized jQuery to a PHP page(e.g ajax.php) where you use $.ajax to submit using post or get.
  2. From your php page, explode the (&) thus separating each attributes. Now you will get attribute1=value, attribute2=value, now you will get a php array variable. e.g$data = array("attribute1=value","attribute2=value")
  3. Do a foreach on $data and explode the (=) so that you can separate the attribute from the value, and be sure to urldecode the value so that it will convert serialized values to the value that you need, and insert the attribute and its value to a new array variable, which stores the attribute and the value of the serialized string.

Let me know if you need more clarifications.


// jQuery Post

var arraydata = $('.selector').serialize();

// jquery.post serialized var - TO - PHP Array format

parse_str($_POST[arraydata], $searcharray);
print_r($searcharray); // Only for print array

// You get any same of that

 Array (
 [A] => 1
 [B] => 2
 [C] => 3
 [D] => 4
 [E] => 5
 [F] => 6
 [G] => 7
 [H] => 8
 )

Modified Murtaza Hussain answer:

function unserializeForm($str) {
    $strArray = explode("&", $str);
    foreach($strArray as $item) {
        $array = explode("=", $item);
        $returndata[] = $array;
    }
    return $returndata;
}

I don't know which version of Jquery you are using, but this works for me in jquery 1.3:

$.ajax({
    type: 'POST', 
    url: your url,
    data: $('#'+form_id).serialize(), 
    success: function(data) {
        $('#debug').html(data);
  }
});

Then you can access POST array keys as you would normally do in php. Just try with a print_r().

I think you're wrapping serialized form value in an object's property, which is useless as far as i know.

Hope this helps!


You just need value attribute name in form. Example :

Form

<form id="login_form">
    <input type="text" name="username" id="a"/>
    <input type="password" name="password" id="b"/>
    <button type="button" onclick="login()">Submit</button>
</form>

Javascript

$(document).ready(function(){});
function login(){
  var obj = $('#login_form').serialize();
  $.post('index.php', obj, function(res){
    alert(res);
  })
}

PHP - index.php

<?php
if(!empty($POST['username']) && !empty($POST['password'])){
  $user = $POST['username'];
  $pass = $POST['password'];
  $res = "Username : ".$user." || Password : ".$pass;
  return $res;
}
?>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to serialization

laravel Unable to prepare route ... for serialization. Uses Closure TypeError: Object of type 'bytes' is not JSON serializable Best way to save a trained model in PyTorch? Convert Dictionary to JSON in Swift Java: JSON -> Protobuf & back conversion Understanding passport serialize deserialize How to generate serial version UID in Intellij Parcelable encountered IOException writing serializable object getactivity() Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly