The Perfect jQuery AJAX Request

If you’re into client-scripting, then jQuery AJAX is probably your thing (if it’s not, perhaps it should be!). jQuery has some fantastic support for AJAX, and implementing it into your web application is so easy it’s stupid. The AJAX functionality in the AJAX library is so flexible, sometimes it’s easy to get lost when you’re trying to do something very simple. I’ve come up with a very basic jQuery AJAX template that I use for just about everything I do, and I thought it might be useful to share.

The Old Way

Did you work with AJAX way back when, when it first came out? You might remember that an AJAX request looked a little like this.

var xmlhttp;
xmlhttp = GetXmlHttpObject();
if(xmlhttp == null){
  alert("Boo! Your browser doesn't support AJAX!");
  return;
}
xmlhttp.onreadystatechange = stateChanged;
xmlhttp.open("GET", "http://www.google.com", true);
xmlhttp.send(null);

function stateChanged(){
  if(xmlhttp.readyState == 4){
    // do something with the response text
    alert(xmlhttp.responseText);
  }
}
function GetXmlHttpObject(){
  // IE7+, Firefox, Chrome, Opera, Safari
  if(window.XMLHttpRequest){
    return new XMLHttpRequest();
  }

  //IE5, IE6
  if(window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
}

In a nutshell, that sucks! All of that code to simply request the contents of Google’s home page, and then alert in the window. That’s not very helpful at all. Alternatively, here is the exact same function written in jQuery:

$.ajax({
  url: 'http://www.google.com',
  success:function(data){
    alert(data);
  }
});

As you can plainly see, the jQuery AJAX method is much easier to wrap your mind around. You give it a URL to request, and then you give it a set of instructions if a successful request is made. Easy!

I understand that it’s not very useful to request the contents of a web page and alert it to your users (in fact, that’s probably pretty annoying), so let’s take it up a notch. jQuery AJAX features a ridiculous amount of customization options, events, and the like to give you a huge amount of flexibility, and it can be hard to find a good place to start. I’ll help you find the starting line, and you can take it from there.

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.

Data Types

We’re loading an RSS feed in this example, so the AJAX function is designed to interpret XML data. jQuery AJAX also understands a number of other data formats, such as HTML, plain text, and even JSON. Find out more about data types at the jQuery AJAX documentation page.

Loading Image

Did you notice the spinning loading image? In the beforeSend function, we’re appending a loading image to our AJAX panel, and we’re then taking it out when a request has completed. If you’re not already aware, be sure to check out the very handy website, Ajaxload. This site allows you to quickly create spinner images of any size and color. They have an impressive array of bars, circles, flowers, and the like, so all your design needs should be satiated by the array of options they provide. It’s always a good idea to include a loading image when working with AJAX requests — depending on the client’s connection speed and a number of other variables, the time it takes to complete a request can vary. Don’t assume it will be lickity-split and lightning fast every time. Give your users some feedback to let them know that you’re working on it.

POST Data

You may have noticed that we’re using POST as the request type. POST requests works just like GET requests, except you get the added flexibility to also send data and other variables along with your request. We sent some dummy data that isn’t used by the RSS feed (data: { postVar1: 'theValue1', postVar2: 'theValue2' }), so feel free to change or omit this line of code in order to customize your AJAX request function. As an example, you could send a variable like userId: '45' to a custom PHP script that in return sends you information about a particular user. The possibilities are endless!

Remember the Search

Take what you’ve learned and venture into the wide world of web development armed with the knowledge you now possess. Destroy post-backs wherever they may live, and always remember that Google hates AJAX and won’t interpret anything on your page that’s loaded via script! Good luck, and happy styling.

29 comments

  1. […] The Perfect jQuery AJAX Request – Kyle Schaeffer – Interface … If you enjoyed this article please consider sharing […]

  2. […] The Perfect jQuery AJAX RequestKyle Schaeffer stellt sein jQuery AJAX-Template vor, mit dem er immer arbeitet. Sehr schön finde ich, dass er direkt auch eine "Loading…"-Meldung eingebaut hat und auch Fehlermeldungen berücksichtigt. […]

  3. Musta says:

    This is a very good start for those who are new to ajax via jquery. I have a suggestion though while you tend to reuse this script I think it would be better to set the type of server request , the url and the error function as global variables and method to avoid rewriting the same stuff in every ajax call that might add.
    Very nice though and thanx

  4. JoseA says:

    This post is excelent.
    Thanks!

    • Lastri says:

      Sure, the ability to do this kind of stuff has been auornd since IE4. But when IE4 first came out, Netscape Navigator version 4 (and even version 3!) still had a fair amount of market share. It’s only been more recently (relatively speaking) that the vast majority of the general public has migrated up to more advanced browser versions. And also only recently that some Big Names began using those techniques in real world applications.

  5. Morpha says:

    Remeber, AJAX POST performs a 2 step process (headers then data), GET is best (only 1 packed of data).

  6. Fluent says:

    I use .load() most of the times .

  7. Mattsk says:

    It appears to be broken. The feed is not loading.

  8. Kyle says:

    Mattsk, thanks for the heads-up. I recently removed the “www.” from my website address, and my JavaScript wasn’t being loaded correctly. It has been fixed!

  9. Beru says:

    Nice post, but i’m curious if somebody can explain me how about multiple ajax call in a second, is it stacked or something else.
    Can we replace previous call of ajax with a newer one, because we never know how many second the ajax will be loaded and return, while the new ajax request will be executed soon. As far as i know THERE IS NO WAY TO STOP AN AJAX after it’s being called.

    • Kyle says:

      Beru, I think in 99% of cases, you really should try and combine all AJAX requests into a single request. The idea of stringing multiple AJAX requests together sounds like a bad idea in my opinion.

      If you really want to string them together, you can use the success and error functions to run subsequent requests (these functions aren’t called until after the initial AJAX request has completed). Simply place a new AJAX request inside one of these functions.

  10. Durgesh says:

    Really nice tutorial.
    Thanks a lot for sharing it with us.

  11. Nikhil says:

    Thanks for that, Kyle. Using this as a basis for most of my ajax posts.

  12. […] found a couple of great posts about loading content through Ajax and Jquery – see kyleschaeffer.com and of course Nettutsplus.com, below is my test and example. var ajax_load = "<img […]

  13. Framp says:

    That’s nice but you can’t make cross-site requests – unless you use something like jsonp (eg: you can’t get the html from http://www.google.com and display it in a alert – well, you can only if you are being executed on google domain)

  14. […] found a couple of great posts about loading content through Ajax and Jquery – see kyleschaeffer.com and of course Nettutsplus.com, below is my test and […]

  15. Ajay says:

    Am doing one project, in that when the checkbox checked result is shown through ajax, in that ajax page there is one jquery function, i dont no how to call that jquey in the ajax page? please reply me as soon as possible, thank u for u r help.

  16. Hope says:

    Thanks man! I hope I am allowed to modify this – lolz

  17. Carl says:

    This is both elegant and understandable. Easy as an Ajax and JQuery beginner, this code makes sense. I do have a question though. Given this blog post is over 2 years old, is there anything you would change now? Is it still your idea of a “perfect ajax request”?

  18. sunita rai says:

    its really very helpful to learn ajax in easiest way.Can we stop multiple time calling for method in ajax call

  19. silvinagreta says:

    I don’t see the loading image though… And I can’t get it to work either.

  20. You should use the .done(), .fail(), and .always() functions as callbacks.

    $.ajax({
    url: ‘http://www.google.com’
    }).done(function(data, status, obj) {
    console.log(“Ajax status: ” + status);
    console.log(“Ajax object: ” + obj);
    console.log(“Ajax data: ” + data);
    }).always(function() {
    console.log(“This code will always run”);
    }).fail(function(data) {
    switch (data.status) {
    case 500:
    alert(“Server error”);
    }
    });

    I always use a “global” Javascript function for handling ajax errors.

    $(document).ajaxError(function (e, data, settings, exception) { AjaxFailed(data); });

    function AjaxFailed(data) {
    // Do something
    }

    Hope this helps.

  21. EJ says:

    ajaxmethod was better. JQuery and webmethods don’t support returning a dataset that you can read by columns and rows the way that you were able to in the old way of handling ajax calls using the ajax DLL. I don’t know if there are other web/app database developers out there who know how to get it done in jquery without a ton of code, … but even to get one record back, I have to do a ton of string parsing to get values that I need from the return data, … jquery ajax is hugely inferior in that way … too bad.

Post a comment

Your email address will not be published. Required fields are marked *