179

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.

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
Gene Bean
  • 1,815
  • 2
  • 12
  • 4
  • 2
    For questions like these I recommend using Firebug to see what data in what format is sent to the server. You can then easily post an example of your data. – chiborg Jun 03 '10 at 09:57

15 Answers15

438

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Chris Allen Lane
  • 6,334
  • 5
  • 25
  • 31
  • 6
    That's the best way of doing it. parse_str($_REQUEST['jquery_serialized_values'], $output); print_r($output); – Andy Dec 28 '10 at 17:06
  • 3
    As the user that gave the accepted answer, I agree that THIS is the correct answer. I gave my answer based on the assumption that the request was being sent via the jQuery ajax $.get/post methods (not sure where I got that from) which does send the output of the serialize() function as standard GET variables. so no string parsing would be required. eg: $.get('ajax.php', $('form').serialize(), function() {}); – Chris Gutierrez Sep 12 '12 at 17:36
  • 1
    This should be the answer. Since the server might not accept more than 1000 input values, I needed a way to send them anyway. So I serialized the form and did send the data as one value. With this answer, I was able to do so. Thanks @chrisallenlane – websupporter Mar 10 '15 at 10:02
  • how to loop through the resulted array `$params`? – StealthTrails Dec 08 '15 at 18:39
  • Please notice that in case you are sending an *email field* for example, it might get urlencoded, like the @ becoming %40 so your PHP *parse_str* shall be accompanied by a urldecode in such case. – Ruslan Abuzant Mar 16 '16 at 00:51
  • From official documentation: `Warning Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2. Dynamically setting variables in function's scope suffers from exactly same problems as register_globals. Read section on security of Using Register Globals explaining why it is dangerous.` – Alejandro Oct 16 '17 at 22:08
  • Best Answer ... this works perfectly when you pass `form.serialize()` and additional parameter in AJAX data object – Kolawole Emmanuel Izzy Feb 06 '21 at 15:06
66

You shouldn't have to unserialize anything in PHP from the jquery serialize method. If you serialize the data, it should be sent to PHP as query parameters if you are using a GET method ajax request or post vars if you are using a POST ajax request. So in PHP, you would access values like $_POST["varname"] or $_GET["varname"] depending on the request type.

The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
Chris Gutierrez
  • 4,750
  • 19
  • 18
  • 9
    This is incorrect. You do indeed need to parse the string that `serialize` returns. See the really popular answer below. – Isaac Lubow Mar 01 '19 at 02:17
56

// 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
 )
Griwes
  • 8,805
  • 2
  • 43
  • 70
Aridane
  • 561
  • 4
  • 2
18
parse_str($_POST['whatever'], $searcharray);
Alfred
  • 21,058
  • 61
  • 167
  • 249
johnlemon
  • 20,761
  • 42
  • 119
  • 178
11

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.

Milad Ghiravani
  • 1,625
  • 23
  • 43
6

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']);
linktoahref
  • 7,812
  • 3
  • 29
  • 51
Omid Akhavan
  • 99
  • 1
  • 6
5

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

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
5

Modified Murtaza Hussain answer:

function unserializeForm($str) {
    $strArray = explode("&", $str);
    foreach($strArray as $item) {
        $array = explode("=", $item);
        $returndata[] = $array;
    }
    return $returndata;
}
Community
  • 1
  • 1
Tomasz Majerski
  • 199
  • 2
  • 7
3

Use:

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

Php get array, dont need unserialize ;)

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Varga Zoli
  • 81
  • 1
  • 5
  • formData = $( '#form' ).serializeArray(); Make sure each input has a name="inputname"; Then you can pass the formData to ajax as type post and retrieve the values as $_POST['inputname']; – Tye Lucas Dec 01 '21 at 20:25
1

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
)
Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
jbz
  • 11
  • 1
1

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!

sixFingers
  • 1,285
  • 8
  • 13
1

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

I have a better function for the same. because if the encoded string contains the array values which is got from an input like 'name="temp_name[]"' so above function does not work.

for this type of data unserialize, use the below function.

function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
    $array = explode("=", $item);
    
    if (preg_match('/(%5B%5D)/', $array[0])) {
          $array[0] = str_replace('%5B%5D','',$array[0]);
          if(array_key_exists($array[0],$returndata)){
                  $returndata[$array[0]][]=$array[1];
          }else{
              $returndata[$array[0]] =array();
              $returndata[$array[0]][]=$array[1];
          }
    }else
    {
        $returndata[$array[0]] = $array[1];
    }   
}
return $returndata;
}
0

Use this in JS part - then you will get it correctly inside your PHP.
the most voted answer would get you in trouble in case
any string would have the & sign.

// this = the form  
const arr = $(this).serializeArray();
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); 

This would give a key/value array when shipped into
you PHP for ajax etc.

Sagive
  • 1,699
  • 1
  • 24
  • 34
0

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.

Jack
  • 10,943
  • 13
  • 50
  • 65
John Dollosa
  • 173
  • 1
  • 1
  • 10