Serialization of object is very important now days, because we are desgining 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 deserialization of string then you will get your own original object. There are many ways in jQuery to convert object in serialized object.
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.
1 |
$('#form').serialize()
|
This method send to server an object and server will received as below string :
1 |
"param1=someVal¶m2=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.
1 |
$('#form').serializeArray()
|
This method send to server an object and server will received as below string :
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.
1 |
data = $('#form').serializeArray()+ '&' + $.param('name':'phpflow');
|
This method send to server a object and server will received as below string :
1 |
a=%5Bparam1%5D&b=someVal¶m2%5D=someOtherVal&name='phpflow'
|
How to get values in php:
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
)
|