HTML and CSS Reference
In-Depth Information
The data from each field in the form is extracted and concatenated into a query string
to submit to the server from the AJAX call. Although this method is functional, it has some
drawbacks. First, a form with many elements will cause this code to get long. As new elements
are added, the code will need to be updated. There is another option in the form of a jQuery
method called serialize() .
Using the jQuery.serialize method
jQuery provides a seamless way to encode data from an HTML form by traversing the form
that's passed into it and looking for input boxes to construct and return a query string. Then
the query string can be posted to the server for processing. The preceding code is rewritten
like this:
$("form").submit(function () {
var qString = $(this).serialize();
alert(qString);
$.ajax({
url: 'processSignUp.aspx',
type: "POST",
data: qString,
success: function (r) {
}
});
return false;
});
In this case, the jQuery.serialize method handles the extraction of the data from all the
input elements and creates the query string. The advantage of using this method— beyond
saving a lot of code—is that the query string is also encoded.
EXAM TIP
The serialize method requires that all elements have the name attribute specified. The preced-
ing code works with the HTML modified as such:
<form id=”signupForm”>
First Name:
<input type=”text” id=”firstName” name=”firstName”/><br/>
Last Name:
<input type=”text” id=”lastName” name=”lastName”/><br/>
<button type=”submit”>Submit</button>
</form>
The serialize method acts on any results from the selector that's passed into the $() seg-
ment of the jQuery. However, the serialize method has some limitations that you should know
about. Only successful controls are serialized—meaning, only controls that are in a valid state.
For input controls such as check boxes and radio buttons, only the ones that are in a selected
state are considered. For radio buttons, because the name attribute must be the same for
 
 
Search WWH ::




Custom Search