How to Use the jQuery ajax() Method

  • google plus

In Brief...

jQuery's core ajax() method is a powerful and straightforward way of creating Ajax requests. To start using it, follow these six steps.

Instructions

  1. Download the jQuery library from jquery.com or find a link to the latest version of jQuery by going to code.jquery.com.
  2. Create an HTML document that includes the jQuery library.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
    
    </body>
    </html>
            
  3. Inside a script element in your HTML document, write jQuery's ready() function, which will wait until the selected object (the HTML document in this case) is ready before executing the code passed into it.
    <script>
        $(document).ready(function() {
    
        });
    </script>
                
  4. Write the ajax() method inside the body of the function passed into the ready() method and pass it an options object as the parameter. The options object must have the URL to send the request to as the first property.
    <script>
        $(document).ready(function() {
            $.ajax({'test.html'});
        });
    </script>
                
  5. After the URL, set any of the optional properties of the options object from the following list:
    • type - The type of the request, "POST" or "GET". Defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all browsers.
    • async - Set to false if the request should be sent synchronously. Defaults to true. Note that if you set this option to false, your request will block execution of other code until the response is received.
    • cache - Whether to use a cached response if available. Defaults to true for all data types except script and jsonp. When set to false, the URL will simply have a cachebusting parameter appended to it.
    • success - A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.
    • error - A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.
    • complete - A callback function to run when the request is complete, regardless of success or failure. The function receives the raw request object and the text status of the request. This function will run after any error or success function, if those are also specified.
    • context - The scope in which the callback function(s) should run (i.e., what this will mean inside the callback function(s)). By default, this inside the callback function(s) refers to the object originally passed to $.ajax.
    • data - The data to be sent to the server. This can either be an object, like {foo:'bar',baz:'bim' } , or a query string, such as foo=bar&baz=bim.
    • dataType - The type of data you expect back from the server. By default, jQuery will look at the MIME-type (from the Content-Type header) of the response if no data type is specified.
    • jsonp - The callback parameter name to send in a query string when making a JSONP request. Defaults to callback. (jQuery will add a parameter callback=XXXXXX to the query string; this option sets the parameter name, and the following option sets the parameter value).
    • jsonpCallback - The value of the callback parameter to send in a query string when making a JSONP request. Defaults to an auto-generated random value.
    • timeout - The time in milliseconds to wait before considering the request a failure.
  6. Use the result of the ajax() method by setting the success property or by chaining another jQuery method to the ajax() method as shown in the following two examples.
    $.ajax({
        url : 'test.txt',
        type : 'GET',
        dataType : 'text',
        success : function(text) {
            $('<h1/>').text(text).appendTo('body');
        }
    });
            
    $.ajax({
        url : 'test.txt',
        type : 'GET',
        dataType : 'text'
    }).done(function(text){
        $('<h1/>').text(text).appendTo('body');
    });
            
    The result of running either of these ajax() methods will be that the contents of test.txt will be loaded into the script and a new h1 element containing the text will be appended to the body of the document.
    Result of Running the Demo Scripts

Related Training

Categories

Courses

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss