Jquery Tutorial : Ajax
- Ajax is the combination of technologies that has made the web 2.0 ⇒ Web Applications.
- In this chapter, you are going to use the power of jQuery to easily use Ajax without worrying about web browser inconsistencies.
We are going to discuss:
- The Ajax technology itself
- The limitations of Ajax
- The shorthand methods provided by jQuery to perform Ajax calls
- The core method for performing Ajax calls
- How to setup Ajax with jQuery
- How to handle Ajax errors with jQuery
- The term Ajax was coined in 2005 and stands for Asynchronous JAvascript and XML.
Before Ajax, the user experience flow when using an application was the following:
- The user clicked on a link to access a new page or sent a form to search information on a website.
- The server received the request and processed it.
- During this time, the user had to wait for his/her browser to load the new page.
Ajax is a combination of technologies that enables the web developer to make asynchronous calls to the server:
XML for interchanging data.
![[Note]](../images/note.png)
Note Other formats can be used for interchanging data such as HTML, JSON or even plain text.
- JavaScript: The XMLHttpRequest object to make asynchronous calls + event binding to process the data once it is there.
Using Ajax, you provide end-users a user experience that feels more like using a desktop application.
- Parts of the page are "refreshed".
- User can still use the web application without having to wait for a new page to load.
- As you might already think about creating big mashups, there is a big limitation to Ajax to take into consideration: The same-origin policy.
- The same origin policy has been implemented into major browsers since Netscape Navigator 2.0.
- It prevents a document or script loaded from one site of origin A from manipulating properties of or communicating with a document loaded from another site of origin B.
- It prevents attacks like hijacking an existing user session or phishing.
For example, with the URL: http://www.company.com/page.html
URL Same origin? Reason YES
YES
NO
Different host
NO
Different protocol
NO
Different port
Browsers check access against the same origin policy when we, for instance:
- Manipulate browser windows
- Request URL via the XmlHttpRequest
- Manipulate frames (including inline frames)
- Manipulate documents (included using the object tag)
- Manipulate cookies
-
There are a lot of shorthand, convenient methods in jQuery to perform Ajax calls and the first one we will discuss here is the
.load()method. The
.load()method allows you to load returned HTML content from the server into a specified part of the page.![[Note]](../images/note.png)
Note You can directly load a static HTML file or a dynamic page that returns HTML content
For example, let us say that you want to load the content of the first
<div class="article">element from an external HTML static file:$('div.article').eq(0).load('article_content.html'); //
In the case that the user has disabled JavaScript, or it is not present (as is the case with text-based browsers), we need to provide progressive enhancement using Ajax. We are going to use a technique called Hijax here:
- Design your application in a way that users without JavaScript can click on links and load the information the old fashioned way (synchronous loading).
- For users with JavaScript, we would intercept the links and dynamically load the content in a certain area of the page.
Say we have a main page with a few hyperlinks in the footer pointing to an about page and a contact page:
<div id="footer"> <ul> <li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>Then let us do some hijax with jQuery:
$(document).ready(function() { $('#footer a').click(function(e) { var url=$(this).attr('href'); //
$('#section').load(url); //
e.preventDefault(); //
});
});
- We have just talked about hijax techniques allowing both support for clients with and without JavaScript.
- However, we still have a big problem: We load the whole external page into a selection.
- How do we select just a part of the external page, so we can control what to load?
Using the same
.load()method, there is a way to specify which part of the page you want to load using selectors:$(document).ready(function() { $('#footer a[href="about.html"]').click(function(e) { var url=$(this).attr('href'); $('#section').load(url) + " #about"; //
e.preventDefault();
});
$('#footer a[href="contact.html"]').click(function(e) {
var url=$(this).attr('href') + " #contact"; //
$('#section').load(url);
e.preventDefault();
});
});The syntax to provide here is a combination of the file to load plus the selector to specify which part of the page to load
![[Note]](../images/note.png)
Note You might think that this reduces the bandwidth since we are precise about which part of the page to load using a selector. But this is not the case. The entire page is still loaded and then the selector is run against it.
-
In the previous section on the
.load()method, we discussed how to load an external static HTML file. -
Using the
.load()method, you can also load a dynamic page that returns HTML content. In a real web application, the data you need to load is generated by server-side scripts operating on a database.
- You can pass arguments to those scripts in order to get the data you want.
The
.load()method accepts a second parameter allowing you to specify query data either as a query string or a JavaScript property object.The two examples below are equivalent:
$('#section').load('recipes.php', 'type=french&name=quiche'); $('#section').load('recipes.php', { type: 'french', name: 'quiche' });
- A few years ago, websites used to share XML data with other websites using APIs to create mashups.
- However XML data is difficult to parse on the client side.
Main alternative to XML ⇒ JSON
- Stands for JavaScript Object Notation.
- The data is structured as plain JavaScript objects.
- There is no parsing required, and it is ready to be used by our scripts.
-
Under the same origin policy, a web page served from one origin cannot normally connect to or communicate with a server located at a different origin ⇒ An exception is the HTML
<script>element. Using JSONP (JSON with Padding), you can take advantage of the
<script>element by specifying the source of the server-side script you want to use.- You specify a callback method of your own in the URL of the script.
- The script returns a JavaScript function call (your function) with the JSON data as a parameter.
Let us take the case of the twitter API, which provides support for JSONP. The URL to call would look like this:
http://search.twitter.com/search.json?callback=processTweet&q=food

jQuery provides a shorthand method that allows you to perform Ajax calls using the JSON format:
jQuery.getJSON().The first argument is the URL for the request.
![[Note]](../images/note.png)
Note If the URL includes a parameter
callback=?thenjQuery.getJSON()uses JSONP instead of JSON. jQuery automatically generates the<script>element and callback function to accept the JSONP response.- The next optional argument is the query data, either as a query string or a JavaScript property object.
- The final optional argument is a callback function executed if the request succeeds. When invoked, it receives the JSON object as an argument.
Let us look an example of that:
// Get the term to search var searchRecipe=$('#txt_recipe_name').val(); // Clean the div tweetsresult $('#tweetsresult').children().remove(); $.getJSON( "http://search.twitter.com/search.json?callback=?", {q: searchRecipe}, function(data) { $.each(data.results, function() { $('<div></div>') .hide() .append('<img src="' + this.profile_image_url + '" />' ) .append('<span><a href="http://www.twitter.com/' + this.from_user + '">' + this.from_user + '</a>' + this.text + '</span>') .appendTo('#tweetsresult') .fadeIn(); }); });
-
All the previously mentioned shorthand methods (and other Ajax methods) internally call the
jQuery.ajax()method. -
Those previously mentioned methods are wrappers around the
jQuery.ajax()method for specific tasks. In case you need more control over your Ajax call, the
jQuery.ajax()method is the one to use. It allows you to use:- GET or POST method
- Error callback
- Different format of data
- etc…
-
This configuration is passed as an argument to the
jQuery.ajax()method as a JavaScript object. Below are some of the configuration options that you can use (For more details, visit http://api.jquery.com/jQuery.ajax/):
asyncBoolean that defines if you want your request to be sent asynchronously or not (
trueby default)cacheDo we want to keep result in the cache or not?
trueby default excepts when thedataTypeisjsonorscriptcompleteThis is the callback function to be called regardless of success or failure. This callback function is passed the raw
XMLHttpRequestobject and a string representing the status of the request as argumentscontextDefines the scope of the callback function (the value of
this)dataThe data to send to the web server. This can be a query string or a JavaScript object
dataTypeSpecifies the expected data type returned by the server. When not specified, jQuery will look at the MIME type of the response
errorDefines the error callback function to be called in case of an error. This callback function is passed the raw
XMLHttpRequestobject and a string representing the status of the request as argumentsjsonpCallback function name in the case of a JSONP request. This value will be used instead of
callbackin thecallback=?part of the query string in the urlsuccessCallback function to be called if the request succeeded. This callback function is passed the data returned from the server, the status string of the request and finally the raw XMLHttpRequest object
timeoutSet the timeout for the request
traditionalSet this to true if you want to use the traditional style of param serialization ⇒ http://api.jquery.com/jQuery.param
typeThe HTTP method to use. Default is GET
urlThe URL to request
- There are some settings that you might want to use in every Ajax call you make.
However, putting those same settings in every Ajax call you make is not convenient.
- Error prone
- Difficult to maintain
jQuery comes with the
jQuery.ajaxSetup()method that allows you to specify global settings so you do not have to include them explicitly in everyjQuery.ajax()call you make.![[Note]](../images/note.png)
Note You can override these global settings in any
jQuery.ajax()call you make.
-
We have seen that there is an
errorparameter where you specify the error callback function. - This error callback function might be the same for every Ajax call.
-
The
.ajaxError()method gives you the ability to configure error handling globally rather than on a per-call basis. These global events are attached to a DOM element where you would show an error message to the user.
$('#ajax_error').ajaxError(function(event,request,settings){ $(this).html("<b>Error when requesting " + settings.url + "</b>"); });![[Note]](../images/note.png)
Note There are also global versions for the
successandcompleteevents using.ajaxSuccess()and.ajaxComplete()methods