Today I came to talk about one of the methods that I find very interesting in Jquery, the serialize().
As its name implies, this method serializes a set of inputs of a form on a string.
This string is standardized and compatible with most server-side language.
This is very useful for example when we want to send a series of data to the server with Ajax.
How?
Well, start creating the form:
<form action='page.php' id='my_form'> <input type='text' name='input_1'> <input type='text' name='input_2'> <input type='text' name='input_3'> </form>
Note that we have created a form of traditional way, but omit the method attribute in the tag <form>, because this will be addressed later.
How to Serialize?
With a line the Jquery lets you do this, let the example:
var formdata = $('#my_form').serialize();
Now the formdata variable is a string serialized like:
input_1=valor1&input_2=valor2&input_3=valor3
The string is in this format key/value concatenated with “&”.
Now that we have the string, just pass it to the server. How? Quite simply with the jQuery Ajax() method:
$.ajax({
type: 'POST';,
url: form.attr('action'),
data: formdata,
success: function(msg){
alert('Sucesso!');
}
});
Remember that we omit the method attribute of the form?
We did this because we are making an Ajax request using the POST method, anyway it would be ignored in our example.
Ajax:
type – Specify the method how data will be sent to the server. In our example we’re using POST.
url - Specifies the page to which the data will be submitted. In our example I’m taking the action attribute of the form, which will cause the data to be submitted to the file page.php.
data – The data to be submitted. The serialized string is passed here.
success – Function to perform when we are successful. In the example, an alert.
Done!
We have created a form, all inputs serialized in a string, send all data to a PHP page via Ajax.
Simple.
Any doubt please comment.
Related Posts:

The Serializing an form with jQuery by Jaydson Gomes, unless otherwise expressly stated, is licensed under a Creative Commons Attribution 2.5 Brazil License.

#1 by Ney Estrabelli at June 14th, 2009
Muito bom o tutorial, mas acho que era preciso colocar que ao receber os dados no PHP é preciso fazer o url_decode para os dados não virem com % (porcentagem, etc).
Abraço
#2 by jaydson at June 14th, 2009
Fala Ney!
Cara, tenho usado bastante essa técnica em meus projetos e não precisei fazer decode da URL, porque submeto os dados via POST mesmo. Ou seja, no PHP eu recebo tudo na $_POST.
Tu teve alguma experiência onde precisou usar o url_decode?
#3 by Aprendiz at July 30th, 2009
Pô brow, coloca ai o exemplo para download!!!!
#4 by Newton Calegari at September 3rd, 2009
Ótima explicação sobre o método serialize() do jQuery.
Quanto a utilização do url_decode para “pegar” os dados no PHP, até agora não foi necessário utilizar.
Abraços,
Newton Calegari