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

Viewed 229411

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.

16 Answers

Use:

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

Php get array, dont need unserialize ;)

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

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.

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

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

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.

Related