Gene Bean
Gene Bean

Reputation: 1845

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.

Upvotes: 182

Views: 241231

Answers (15)

Sagive
Sagive

Reputation: 1817

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.

Upvotes: 1

Salim Mansoori
Salim Mansoori

Reputation: 61

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

Upvotes: 0

Chris Allen Lane
Chris Allen Lane

Reputation: 6442

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

Upvotes: 439

Omid Akhavan
Omid Akhavan

Reputation: 99

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']);

Upvotes: 6

  Varga Zoli
Varga Zoli

Reputation: 91

Use:

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

Php get array, dont need unserialize ;)

Upvotes: 3

Lagan Script
Lagan Script

Reputation: 11

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

Upvotes: 1

Tomasz Majerski
Tomasz Majerski

Reputation: 199

Modified Murtaza Hussain answer:

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

Upvotes: 5

Chris Gutierrez
Chris Gutierrez

Reputation: 4755

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"

Upvotes: 67

Milad Ghiravani
Milad Ghiravani

Reputation: 1683

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.

Upvotes: 11

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

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

Upvotes: 5

John Dolls
John Dolls

Reputation: 193

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.

Upvotes: 0

jbz
jbz

Reputation: 11

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
)

Upvotes: 1

johnlemon
johnlemon

Reputation: 21449

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

Upvotes: 18

Aridane
Aridane

Reputation: 561

// 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
 )

Upvotes: 56

sixFingers
sixFingers

Reputation: 1295

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!

Upvotes: 1

Related Questions