Good tutorial on AJAX requests using jQuery

http://kyleschaeffer.com/best-practices/the-perfect-jquery-ajax-request/

 

The Perfect AJAX Request

I’m fairly positive that by using the term perfect, I’m going to get a good amount of nay-sayers telling me why jQuery AJAX sucks, but that’s not what I’m getting at. This jQuery function is perfect in the sense that it handles 99% of all the AJAX requests you’ll ever need to make, it includes a success and failure function to ensure that users get the proper feedback they need, and you’ll get a spinning loading image while the request is being processed to boot. Throw on top of that the fact that it’s extremely easy to use, and I’d say you have something that’s pretty damned close to perfect, at least in my book. Here is the template:

$.ajax({
  type: 'POST',
  url: 'http://kyleschaeffer.com/feed/',
  data: { postVar1: 'theValue1', postVar2: 'theValue2' },
  beforeSend:function(){
    // this is where we append a loading image
    $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
  },
  success:function(data){
    // successful request; do something with the data
    $('#ajax-panel').empty();
    $(data).find('item').each(function(i){
      $('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
    });
  },
  error:function(){
    // failed request; give feedback to user
    $('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
  }
});

In this case, I’m loading my site’s RSS feed into a <div/> with an ID of ajax-panel. What does it look like exactly, you ask? Let’s try it out.