January 19, 2012

jQuery Ajax Tutorial and Examples

« Complex Sorting with Java Comparator | Main | Don't walk the walk for your employees »

JQuery provides an Ajax (Asynchronous JavaScript and XML) wrapper function, which is very flexible to use, browser independent and customizable. At first I will describe some basic settings and functions. After that I will show you two examples. The first will be very short and simple, the second will show you more functionality and possible parameters of the jQuery jQuery.ajax() function. Last but not least I will show up some derived methods, that facilitate some standard or often used requests.

Prerequisites

For using jQuery you have to include the jQuery script URL into your HTML head tag. I recommend to use the jQuery JS resource URL from the Google CDN (see why). If you want to download the JQuery library and install on your webserver go to the jQuery download page.

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <!-- or -->
    <script type="text/javascript" src="http://yourdomain.tld/js-path/jquery.min.js"></script>
  </head>
  <body></body>
</html>

Basic Method Structures

//url: request URL
//settings
jQuery.ajax(settings);
//shorter
$.ajax(settings);

If you don't need to customize the default settings. You can use the following calling structure.

jQuery.ajax(url);
//or shorter
$.ajax(url);

Basic Settings:

  • Of course the most important setting is url, which contains the request URL.
  • The next important setting is type, that defines the request method type (GET, PUT, POST, DELETE, etc.).
  • The dataType setting defines your expected response mime type from the server (e.g. application/json)
  • The headers setting contains additional request header values (e.g. session id)
  • The data setting includes the data, which you want to send to the server (e.g. json string, interesting for PUT and POST request method)
  • The async setting allows you to use only synchronous calls. Default is falsepre.
  • In most cases the default of the cache setting is true. It means, that not a timestamp is appended to the request URL. So the browser caches the responses. You can disable this parameter with the value false.

The settings error and success defines the success or error handling callback functions.

$.ajax({
  ..
  //includes the response status (e.g. 404 not found) and an error message
  error: function(xhr, status, error) {
    alert('(' + status + ', ' + error + ')');
  },
  success: function(data) {
    alert(data);
  }
});

You can find all settings on the following jQuery web page.

If you want to override the default value globally you can use the jQuery ajaxSetup method.

  //all $.ajax() requests will be executed synchronously, not really Ajax
  $.ajaxSetup({
      async: false
  });

Example 1: Load and Embed HTML snippet

I saved an external HTML with the location http://developers-blog.org/resources/jquery-ajax/snippet.html.

Hello developers-blog.org reader.

After a click on load the jQuery Ajax method will get the HTML snippet and will append the content to the white box.

Load The Snippet
//wait for HTML document
$(document).ready(function() {
  $('#load-button').click(function() {
    $.ajax({
      url: 'http://developers-blog.org/resources/jquery-ajax/snippet.html',
      success: function(data) {
        $('#load-button').empty();
        $('#load-button').append(data); 
      }
    });
  });
});
 

Example 2: Load JSON and create List

This examples load an JSON resource and creates a HTML list

Load JSON

JSON Code:

[ 
{"name":"Superman"},
{"name":"Spiderman"},
{"name":"Flash Gordon"}
]

jQuery Ajax Code:

//wait for HTML document
$(document).ready(function() {
  $('#load-button-json').click(function() {
    $.ajax({
      url: 'http://developers-blog.org/resources/jquery-ajax/heroes-list.json',
      type: "GET",
      dataType: "json",
      cache: false,
      success: function(data) {
        $('#load-button-json').empty();
        var $ul = $('
    '); $('#load-button-json').append($ul); $.each(data, function() { $ul.append('
  • ' + this.name + '
  • '); }); } }); }); });

    Derived methods

    The first derived method from the jQuery Ajax wrapper function that I often use is the getJson() method.

    $.getJSON('ajax/data.json', function(data) {
    });
    

    Another method that is sometimes useful is the post() method.

    $.post("/resource", { firstName: "Rafael", secondName: "Sobek" } );
    

    Technorati Tags:

    Posted by rafael.sobek at 11:06 PM in Javascript

     

    [Trackback URL for this entry]

    Pingback: JQuery Ajax - Introduction &amp; Examples | Ajax | Syngu at So, 22 Jan 6:55 AM

    jQuery Ajax
    &nbsp;Ajax Read the original post on DZone... Related topics Do you like this post? You may

    Comment: Lasna at Sa, 11 Feb 12:00 PM

    Try looipng thru your array in Model and use “or_like” instead “like” after first item.

    Comment: Brij at Sa, 7 Apr 10:38 PM

    Hi,

    What if I want to show something like
    Name, Job and Department in stead of Name only.

    Also how would I loop through it.
    Could you provide a little more lines in the "load Json..." section

    Comment: recetas at Di, 9 Apr 2:25 AM

    I have some problems with IE7 and some AJAX code, you should continue to provide support for IE7

    Your comment:

    (not displayed)
     
     
     

    Live Comment Preview:

     
    « January »
    SunMonTueWedThuFriSat
    1234567
    891011121314
    15161718192021
    22232425262728
    293031    
           
     
    test