How to use the Ajax powerhouse - $.ajax()
All other jQuery Ajax methods are simply convenient methods to hide the details of how Ajax is done. But with the convenience we loose some capabilities. The $.ajax() method gives those capabilities back to us. Using the $.ajax() method we can even ignore the convenience functions of .load(), .get(), .post(), etc.
The $.ajax() method takes a single parameter - an object with property/value combinations for our needs. These options are all defined in the official documentation, but we will cover the basics here.
The following sample is serves the same purpose as the .load() method:
$.ajax({
url : "page2.htm",
success : function (data) {
$("#mydiv").html(data);
}
});
Remember whitespace is ignored, so that could ALL be on a single line. But this style is a little more readable.
We use the url property to indicate what page we want to load. When we have successfully loaded our data, we call a function (declared inline) and pass the data as a parameter. Then we set the HTML of our target DIV to whatever is in the data variable.
This is great, except all too often we need to pass details to the server side page, or handle the results in a different format - xml, json, etc. And what about when the request encounters an error? And how do we POST data to a server side page, rather than using an HTTP GET type of request?
Here's a typical sample of what the $.ajax() call would look like that can handle all of the above issues. We'll dissect this below.
$.ajax({
url: "serverpage.php",
type: "POST",
data: "param1=one¶m2=" + $("#input2").val(),
dataType: "json",
error: function (xhr, desc, exceptionobj) {
alert(xhr.responseText);
},
success : function (json) {
if (json.error) { alert(json.error); return; }
var output = "";
for (p in json) {
output += p + " : " + json[p] + "\n";
}
alert("Results: \n\n" + output);
}
});
Lets tackle this line by line:
- First we indicate we want an Ajax call (the $.ajax({ line)
- url: here we are specifying the file we want to call. This can be a relative or absolute path. Keeping in mind that typical Ajax calls must be in the same domain as the calling page.
- type: We indicate that we want an HTTP POST rather than the default HTTP GET
- data: We indicate the variables and values to pass to our server side page. This is in the same format we would use in a GET operation - the data that would come after the ? in a normal URL, and each parameter seperated by an & character.
- dataType: This indicates what kind of data we are expecting back from the server. The default is "html" or "xml" (jQuery tries to guess based on the results). But we can also use the types of "script", "json", and "text".
- error: Here we are indicate what to do if we encounter an error. The types of errors found here can be Page Not Found, Server Error, etc. Typical HTTP errors. This gives us a chance to gracefully handle these situations. The function being called is passed 3 parameters - the XMLHTTPRequest object in use, a description of the error (if available), and an exception object (if available). The XMLHTTPRequest object normally has the error text in it's responseText property, so we often want to see what that says - either in an alert or in the HTML of a page element.
- success: The success function indicates what we want to happen when the Ajax request has been successfully completed. The data is passed as the parameter of the specified function, and we can name that parameter as desired. Once we have that data we can process it however we desire. The remainder of our sample is totally arbitrary and should be replaced with code more pertinent to your own needs.
- the "if (json.error)" line: Sometimes we get a valid response that does not trigger the Ajax error handler, but our business logic says we have an error. This may be indicated via an "error" property (an arbitrary name in this case). So we may need to check if we have a business error (rather than a server or syntax error), and take appropriate action. This type of coding is highly dependent on your own coding needs.
- the var output=""; line: Here we are simply declaring a variable that we'll show to the user later on.
- The for loop: we loop over each of the properties of the returned object, and add the property name, and the value contained in that property to our output string. (the for..in type of loop is core JavaScript)
- the alert line: And finally we show the user what we received.
With these lines alone we can emulate the .load(), $.get(), $.post(), and get $.getJSON() methods, but still only need to learn a single method. The $.ajax() method gives us the greatest flexibility over working with Ajax via jQuery. An exploration of the other options will expand our capabilities here even more.