What is Ajax

The XMLHttpRequest object is part of a technology called Ajax (Asynchronous JavaScript and XML). Using Ajax, data could then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page.

With the widespread adoption of the XMLHttpRequest object it quickly became possible to build web applications like Google Maps, and Gmail that used XMLHttpRequest to get new map tiles, or new email without having to reload the entire page.

Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it’s imperative that a callback be used to handle the response.

Unfortunately, different browsers implement the Ajax API differently. Typically this meant that developers would have to account for all the different browsers to ensure that Ajax would work universally. Fortunately, jQuery provides Ajax support that abstracts away painful browser differences. It offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().

jQuery’s Ajax-Related Methods

// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "post.php",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
$( "<h1>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\">").html( json.html ).appendTo( "body" );
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
});

 

Ajax and Forms

jQuery’s ajax capabilities can be especially useful when dealing with forms.

Serialization

Serializing form inputs in jQuery is extremely easy. Two methods come supported natively: .serialize() and .serializeArray(). While the names are fairly self-explanatory, there are many advantages to using them.

The .serialize() method serializes a form’s data into a query string. For the element’s value to be serialized, it must have a name attribute. Please note that values from inputs with a type of checkbox or radio are included only if they are checked.

// Turning form data into a query string
$( "#myForm" ).serialize();
// Creates a query string like this:
// field_1=something&field2=somethingElse

While plain old serialization is great, sometimes your application would work better if you sent over an array of objects, instead of just the query string. For that, jQuery has the .serializeArray() method. It’s very similar to the .serialize() method listed above, except it produces an array of objects, instead of a string.

// Creating an array of objects containing form data
$( "#myForm" ).serializeArray();
// Creates a structure like this:
// [
// {
// name : "field_1",
// value : "something"
// },
// {
// name : "field_2",
// value : "somethingElse"
// }
// ]

Client-side validation

Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc…, or checking an “I agree…” box.

// Using validation to check for the presence of an input
$( "#form" ).submit(function( event ) {
// If .required's value's length is zero
if ( $( ".required" ).val().length === 0 ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});

check for invalid characters in a phone number:

// Validate a phone number field
$( "#form" ).submit(function( event ) {
var inputtedPhoneNumber = $( "#phone" ).val();
// Match only numbers
var phoneNumberRegex = /^\d*$/;
// If the phone number doesn't match the regex
if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});

Leave a Reply

Your email address will not be published.

*