Serialization of Object in php and jQuery

Serialization of object is very important now days, because we are designing more responsive web application/mobile application. We need serialized object for ajax request as well as for web service. The target object can be JSON data object or simple form element. Serialization is used to storing or passing object values around without losing their type and structure.
The jQuery Serialization methods convert them into string and send as query string to server side. You can use de-serialization of string then you will get your own original object. There are many ways in jQuery to convert object in serialized object.

jQuery serialize to php array Using AJAX

There are following method is used for serialization:

1 – serialize() : This is common method to use send form values as a serialized object to server. The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls.

Select Code
1
$('#form').serialize()

This method send to server an object and server will received as below string :

Select Code
1
"param1=someVal&param2=someOtherVal"

2 – serializeArray() : This method behaves as like names, it is converting object in array manner. The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls.

Select Code
1
$('#form').serializeArray()

This method send to server an object and server will received as below string :

Select Code
1
2
3
4
5
6
7
8
{
    name: "param1",
    value: "someVal"
  },
  {
    name: "param2",
    value: "someOtherVal"
  },

3 – jQuery.param() : Sometimes when you do an Ajax form post in jQuery, you need to merge another object into your post data. The solution is to serialize the existing form data using jQuery’s $().serialize method. Then we use the $.param() utility method to create a serialized version of any JavaScript object or array. Simply concatenate the two objects.

Select Code
1
data = $('#form').serializeArray()+ '&' + $.param('name':'phpflow');

This method send to server a object and server will received as below string :

Select Code
1
a=%5Bparam1%5D&b=someVal&param2%5D=someOtherVal&name='phpflow'

How to get values in php:

Select Code
1
2
3
4
5
6
7
8
9
$params = array();
parse_str($_GET, $params);
print_r($searcharray); 
// You get any same of that

 Array (
 [param1] => someVal
 [param2] => param2
 )
These functions return a string representations of an array or an object which can than be decoded back into array/object.

  • Rajbir Singh

    Thanks for submiting such a wonderful article. Great article. Thanks once again