How do I PHP-unserialize a jQuery-serialized form?

PhpJquerySerialization

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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"

Solution 3 - Php

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

Solution 4 - Php

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

Solution 5 - Php

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.

Solution 6 - Php

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

Solution 7 - Php

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

Solution 8 - Php

Modified Murtaza Hussain answer:

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

Solution 9 - Php

Use:

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

Php get array, dont need unserialize ;)

Solution 10 - Php

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!

Solution 11 - 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
)

Solution 12 - Php

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

Solution 13 - Php

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.

Solution 14 - Php

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

Solution 15 - Php

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

Solution 16 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGene BeanView Question on Stackoverflow
Solution 1 - PhpChris Allen LaneView Answer on Stackoverflow
Solution 2 - PhpChris GutierrezView Answer on Stackoverflow
Solution 3 - PhpAridaneView Answer on Stackoverflow
Solution 4 - PhpjohnlemonView Answer on Stackoverflow
Solution 5 - PhpmghhgmView Answer on Stackoverflow
Solution 6 - PhpOmid AkhavanView Answer on Stackoverflow
Solution 7 - PhpMurtaza Khursheed HussainView Answer on Stackoverflow
Solution 8 - PhpTomasz MajerskiView Answer on Stackoverflow
Solution 9 - Php Varga ZoliView Answer on Stackoverflow
Solution 10 - PhpsixFingersView Answer on Stackoverflow
Solution 11 - PhpjbzView Answer on Stackoverflow
Solution 12 - PhpLagan ScriptView Answer on Stackoverflow
Solution 13 - PhpJm DollosaView Answer on Stackoverflow
Solution 14 - PhpNikoView Answer on Stackoverflow
Solution 15 - PhpSalim MansooriView Answer on Stackoverflow
Solution 16 - PhpSagiveView Answer on Stackoverflow