The jQuery serialize()
method turns the form values into a valid querystring, as such you can simply append to the string:
firstName=Maurizio&lastName=Tarchini
Useful, right?
Lets take an example:
<p><em></em></p><form action="#" id="input_form"><em>
first name: <input name="firstName" type="text"><br>
last name: <input name="lastName" type="text"><br>
email: <input name="email" type="text"><br>
<input value="send" name="submit" type="submit"> <br>
</em></form><p></p>
Lets say you want to send the form's data like first name, last name etc. using ajax to some other page,
Then what you will write in
<p>*$("#input_form").submit(function(){
var first name = $('input[name=first name]').val();
var last name = $('input[name=last name]').val();
var email = $('input[name=email]').val();
var querystring = "first name="+first name+"&last name="+last name+"&email="+email;</p>
<pre> $.ajax({
url: 'elaboration.php',
type: "POST",
data: querystring,
success: function(data) {
//code to execute
}
});
return false;
</pre>
<p>});*</p>
As you can see, in submit event, I start extracting one at a time the data contained in the form fields.
Afterwards, I create the querystring variable in the format requested by the ajax method (name=value&name=value).
using the serialize() method we can achieve everything with a single and simple line of code.
How to use the serialize method?
Simple. Instead of this ?
<p>$("#input_form").submit(function(){
var first name = $('input[name=first name]').val();
var last name = $('input[name=last name]').val();
var email = $('input[name=email]').val();
var querystring = "first name="+first name+"&last name="+last name+"&email="+email;</p>
<p>Enough doing this?</p>
<p>$("#input_form").submit(function(){
var querystring = $(this).serialize();
}</p>
Will Give you the query String.
0 Comment(s)