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

Advertisements
By Rz Rasel Posted in jQuery

One comment on “The Perfect AJAX Request

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s