Sunday, February 9, 2014

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('
/images/loading.gif
" alt="Loading..." />'); }, success:function(data){ // successful request; do something with the data $('#ajax-panel').empty(); $(data).find('item').each(function(i){ $('#ajax-panel').append('

' + $(this).find('title').text() + '

' + $(this).find('link').text() + '
'); }); }, error:function(){ // failed request; give feedback to user $('#ajax-panel').html('
Oops! Try that again in a few moments.
'); } });
In this case, I’m loading my site’s RSS feed into a 
 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 GETrequests, 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 likeuserId: '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.

4 comments:

oakleyses said...

jordan pas cher, chanel handbags, nike outlet, michael kors pas cher, kate spade outlet, replica watches, longchamp pas cher, nike free, jordan shoes, christian louboutin shoes, nike free run, louis vuitton outlet, oakley sunglasses, ray ban sunglasses, polo ralph lauren, ugg boots, christian louboutin uk, air max, louis vuitton outlet, ugg boots, tiffany jewelry, polo ralph lauren outlet online, burberry pas cher, prada outlet, nike air max, gucci handbags, sac longchamp pas cher, ray ban sunglasses, louboutin pas cher, louis vuitton, uggs on sale, tiffany and co, oakley sunglasses, louis vuitton outlet, ray ban sunglasses, longchamp outlet, louis vuitton, longchamp outlet, replica watches, nike roshe, polo outlet, oakley sunglasses, cheap oakley sunglasses, oakley sunglasses wholesale, christian louboutin, christian louboutin outlet, tory burch outlet

oakleyses said...

lululemon canada, nike air max, burberry outlet, oakley pas cher, burberry handbags, coach outlet store online, kate spade, michael kors outlet, michael kors, nike air force, true religion jeans, true religion outlet, michael kors, polo lacoste, nike tn, new balance, abercrombie and fitch uk, michael kors outlet, uggs outlet, michael kors outlet, ralph lauren uk, michael kors outlet online, replica handbags, coach outlet, true religion outlet, coach purses, nike free uk, sac vanessa bruno, mulberry uk, michael kors outlet online, michael kors outlet online, michael kors outlet online, north face, uggs outlet, converse pas cher, hogan outlet, nike air max uk, hollister pas cher, sac hermes, nike roshe run uk, hollister uk, nike air max uk, true religion outlet, timberland pas cher, vans pas cher, ray ban pas cher, guess pas cher, ray ban uk

oakleyses said...

ipad cases, beats by dre, iphone 6 cases, ferragamo shoes, wedding dresses, hollister clothing, p90x workout, instyler, asics running shoes, nike huaraches, hermes belt, north face outlet, s6 case, babyliss, nfl jerseys, hollister, iphone 6 plus cases, insanity workout, ralph lauren, iphone cases, iphone 6s plus cases, bottega veneta, new balance shoes, longchamp uk, iphone 6s cases, giuseppe zanotti outlet, nike roshe run, mont blanc pens, herve leger, oakley, lululemon, timberland boots, nike air max, iphone 5s cases, ghd hair, valentino shoes, louboutin, nike trainers uk, celine handbags, north face outlet, baseball bats, vans outlet, abercrombie and fitch, chi flat iron, soccer jerseys, mac cosmetics, mcm handbags, soccer shoes, jimmy choo outlet, reebok outlet

oakleyses said...

supra shoes, marc jacobs, canada goose, converse outlet, toms shoes, ugg uk, ugg pas cher, canada goose outlet, canada goose, nike air max, louis vuitton, karen millen uk, doudoune moncler, converse, louis vuitton, vans, gucci, montre pas cher, moncler outlet, canada goose uk, canada goose outlet, moncler, pandora jewelry, barbour uk, moncler outlet, juicy couture outlet, louis vuitton, canada goose, pandora uk, coach outlet, swarovski crystal, ugg,uggs,uggs canada, juicy couture outlet, links of london, louis vuitton, louis vuitton, hollister, swarovski, canada goose outlet, ray ban, moncler, ugg, barbour, ugg,ugg australia,ugg italia, replica watches, pandora charms, moncler uk, pandora jewelry, wedding dresses, canada goose jackets, hollister, lancel