Jquery Tutorial : Ajax

7. 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

7.1. What Is Ajax?

  • 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]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.

7.2. Limitations Of Ajax

  • 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

  • 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

7.3. Load HTML Content: The .load() Method

  • 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]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'); // 1

    1

    Dynamically insert the content of the static file (content inside the <body> tag) in the specified selector

7.4. Hijax With jQuery

  • 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> 1
        <li><a href="contact.html">Contact</a></li> 2
      </ul>
    </div>

    1 2

    The way hyperlinks are written makes them still usable by users that do not have JavaScript available
  • Then let us do some hijax with jQuery:

    $(document).ready(function() {
      $('#footer a').click(function(e) {
        var url=$(this).attr('href'); // 1
        $('#section').load(url); // 2
        e.preventDefault(); // 3
      });
    });

    1

    Get the url to load

    2

    Call the load method with the right URL

    3

    Calling preventDefault() prevents the user from following the hyperlink

7.5. Select In Detail What To Load

  • 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"; // 1
        e.preventDefault();
      });
      $('#footer a[href="contact.html"]').click(function(e) {
        var url=$(this).attr('href') + " #contact"; // 2
        $('#section').load(url);
        e.preventDefault();
      });
    });

    1 2

    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]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.

7.6. Advanced Loading Using The .load() Method

  • 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'
      });

7.7. JSON and JSONP

  • 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.

7.8. Load JSON Data: The .getJSON() Method

  • 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 1

    1

    Gets all the tweets mentioning food in a JSON structure and passes this as a parameter to our function "processTweet"
  • 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]Note

      If the URL includes a parameter callback=? then jQuery.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();
        });
    });

7.9. The Main Ajax Method: .ajax()

  • 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/):

    async

    Boolean that defines if you want your request to be sent asynchronously or not (true by default)

    cache

    Do we want to keep result in the cache or not? true by default excepts when the dataType is json or script

    complete

    This is the callback function to be called regardless of success or failure. This callback function is passed the raw XMLHttpRequest object and a string representing the status of the request as arguments

    context

    Defines the scope of the callback function (the value of this)

    data

    The data to send to the web server. This can be a query string or a JavaScript object

    dataType

    Specifies the expected data type returned by the server. When not specified, jQuery will look at the MIME type of the response

    error

    Defines the error callback function to be called in case of an error. This callback function is passed the raw XMLHttpRequest object and a string representing the status of the request as arguments

    jsonp

    Callback function name in the case of a JSONP request. This value will be used instead of callback in the callback=? part of the query string in the url

    success

    Callback 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

    timeout

    Set the timeout for the request

    traditional

    Set this to true if you want to use the traditional style of param serialization ⇒ http://api.jquery.com/jQuery.param

    type

    The HTTP method to use. Default is GET

    url

    The URL to request

7.10. Ajax Global Settings

  • 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 every jQuery.ajax() call you make.

    [Note]Note

    You can override these global settings in any jQuery.ajax() call you make.

7.11. Error Handling

  • We have seen that there is an error parameter 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]Note

    There are also global versions for the success and complete events using .ajaxSuccess() and .ajaxComplete() methods