Menu

The Power of jQuery with Ajax

Advertisement

The Power of jQuery with Ajax

As the web evolves, new technologies are emerging and uniting in remarkable ways. The combination of Ajax and jQuery, in particular, is one of the most powerful unions to date.

The purpose of this article is to give a brief and generalized overview of both Ajax and jQuery, and also discuss how jQuery has made Ajax development easier than ever before.

What is Ajax?

Since its conception in 2005[1], Ajax (Asynchronous JavaScript and XML) has changed the web as we know it today. It’s helped websites evolve into Rich Internet Applications (RIAs) by allowing web pages to make direct requests to web servers without reloading the page. This capability is vital in replicating the rich user experiences achieved in client applications.

Ajax in Practice

Let’s say that you have a login form for your web application. To ensure that the provided login name and password entered by the user is a match without using Ajax, your web application would have to load a whole new web page that shows an account screen if the login was successful, or show an error screen if the login failed. This is the old way of handling logins.

A more savvy approach to this problem would be to check if the login and password is correct using Ajax.

Here’s how Ajax would work in this instance: Once the user has typed in a login name and password and submitted the login web form, you could have a JavaScript function that invokes an Ajax call that sends two parameters — the login name and password.

The web server (usually through a server-side script/language such as PHP) takes the two parameters and then queries your user database to see if there is a match.

If there is a match found in your database, then the web server can return a success flag. Otherwise, the web server could return an error message.

Next, you would then have a JavaScript function that accepts the Ajax response. If the response is successful, it could use window.location to send the user to their account screen.

If the response contains an error message, the application can display the error on the screen without ever reloading the page.

The main thing to take away from this is that you don’t have to reload an entire page just to handle username/password verification, making your web application more responsive and, if the page is heavy, saving you some significant bandwidth.

What is jQuery?

Released in January of 2006[2], jQuery is a cross-browser JavaScript library designed to simplify the client-side script of HTML.

Used by close to a million websites[3], jQuery is the most popular JavaScript library in use to date.

jQuery makes it easy to handle DOM objects, events, effects and Ajax, automatically takes care of JavaScript leaks, and has countless third-party plugins.

The Problem with Ajax

Despite its revolutionary impact on the web, Ajax can be difficult to use even for veteran developers.

People will usually create their own custom functions to handle Ajax calls so that the functionality can be reused across a web application. This can become very tedious when a web application makes use of different types of Ajax calls — such as the ability to handle both synchronous and asynchronous calls — or the ability to handle different response formats such as string messages, HTML, CSV, XML, JSON, etc.

As a professional web developer, I’ve personally spent countless hours building custom methods to handle Ajax calls.

Traditional Ajax calls usually take on the following form:

function httpRequest(id) {
  if (window.XMLHttpRequest) { // code for IE7+, FF, Chrome, Opera, Safari
    http=new XMLHttpRequest();
  }
  else { // code for IE6, IE5
    http=new ActiveXObject("Microsoft.XMLHTTP”);
  }
  http.onreadystatechange=function() {
    if (http.readyState==4 && http.status==200) {
      response = http.responseText;
      // do something with response
    }
  }
  dest=”servlet.php?id=” + id;
  http.open("GET”, dest);
  http.send();
}

If your web application only uses one Ajax call, it’s not that big of a deal to implement. The problem occurs, however, when your web application leverages lots of Ajax calls and you try to break the code apart to make it reusable.

The idea of Ajax is to send a request to some web server, wait for a response, and update your HTML page. It would be convenient to create a custom function like httpRequest() that takes two parameters — a request URL and a response function — that could be reused throughout your system.

Once you start setting this up, however, you’ll immediately see that the simple task of making an Ajax call suddenly becomes a nightmare when you try to construct response function evaluations using eval() and figuring out how to make your new function handle synchronous calls, asynchronous calls, and different response formats.

At the end of the day, the simple idea of creating a custom httpRequest() function quickly turns into a big project.

The other advantage of jQuery is that it has additional Ajax functions and methods that you can use, which can further reduce development and debugging time.

Hello Ajax. Meet jQuery.

Among other advantages, one of my favorite features of jQuery is its ability to leverage Ajax with very little effort. To make an Ajax call, you can do something like this:

$.Ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
    alert( "Data Saved: " + msg );
  }
});

If you’ve developed Ajax applications before without jQuery, you’ll immediately see the value here. jQuery has put all of the properties of Ajax into one simple API. You can control everything including the url, cache, success function, data type, and even synchronization, all from one neat declaration. It’s nothing short of beautiful.

Get Started with Ajax + jQuery

If you’re not using a JavaScript Web Development framework like jQuery or MooTools yet, and you’re planning on creating responsive web applications, you should leverage these awesome libraries.

For jQuery, the following list highlights some tutorials you can check out.

References

  1. Ajax: A New Approach to Web Applications
  2. jQuery 1.0
  3. jQuery Usage Statistics

Related Content

About the Author

Eric Rowell is a professional web developer and designer who is fascinated with everything related to the web, including RIAs, emerging technology, and social media marketing. He is the Founder and Chief Editor of Web Krunk and loves HTML, HTML5, CSS, JavaScript, Ajax, jQuery, Flash, PHP and Java. You can follow him on Twitter at @webkrunk.

This was published on Jun 25, 2010

36 Comments

Jordan Walker Jun 25 2010

Very nice article, AJAX has really pushed the bounds with Server – Client interactions.

Very nice article and very well explained.

Jae Xavier Jun 25 2010

i like using ajax to cleaning my bathrooms also. comes in handy.

Elliott Jun 25 2010

Nice article. Love the way jQuery handles AJAX.

(by the way your Twitter link doesn’t work, it’s repeating the URL in the address bar twice)

Manmohanjit Singh Jun 25 2010

I’ve used Ajax site wide once before, many of my readers hated it. I had to remove it. Now I only use it for forms.

Good article.

Spelling mistake:

“Used close to a million websites using jQuery”

i think you meant “there are close the a million websites using jquery”

Great Article

Jacob Gube Jun 26 2010

@Elliott: I can’t replicate the issue, if you encounter the issue again, you’d rock if you could email me a screenshot and maybe details of your set-up (browser version, OS, etc.) so I can try and reproduce the bug. I’ve had issues before with the Retweetmeme button, where when you click on it, it’s blank.

@Manmohanjit Singh: Ajax for loading your web page content? That’s typically not a good application of Ajax, especially when you break bookmarking/back button capabilities.

@Nico: My fault. Corrected it, thanks for bringing my attention to it.

Tom Walters Jun 26 2010

@Jacob Gube I’ve got the same issue, here is a screen-shot – http://drp.ly/1gtDg3 – I’m on OSX Snow Leopard, FF3.6.4

used ajax via jQuery in my final year project based on php, great article!

Christoph Düngel Jun 26 2010

THX for this great article

used this technique on my current project.
jQuery is short for jesusQuery.

r6media Jun 27 2010

Thanks for this great and detailed tutorial,I have used ajax in previous projects.

Jacob Gube Jun 27 2010

@Tom Walters: Ah! Thanks for the screengrab. Fixed it. That was my fault.

Erwicki Jun 27 2010

Great artcile!
But just a question: why did you wait such a long time to publish it? I have seen articles like this one at least one year ago!

Great Article, I love jQuery. I have used a few other ajax framworks and for me, jQuery is so much more user friendly and useable.

Very informative article here, i have used Ajax/jQuery plug-ins on a number of projects, however only now I’m starting to dive into the coding trying to customise my own applications for forms etc.

well jquery is one of the popular choice in javascript framework, ajax in jquery (and other javascript framework) coding style surely saving time than doing in raw javascript

i agree with aditia, but its not really just a jquery thing well is it? You’ve nearly the same Functions with most other JS-Library’s anyhow, in my book ajax should not be sold as a method, but as an concept. And, to be honest, that knowledge should already be part of the ABC for every serious Webworker, anyhow, interesting now will be a continuous server -> client communication post-commet using HTML5 Methods.

Well, anyhow, great Article :) Will have it in my backpoket if someone asks me again what jquery and ajax are ;)

Jennifer R Jun 29 2010

Could you make a tutorial about Ajax for wordpress theme design? I need to develop some premium WordPress theme :)

Fuad NAHDI Jun 30 2010

Thank you for this excellent article. Like this very much :)

nice post

and what about the .load() function?
sometimes easier, sometimes not, sufficient for me, most of the time.
-> http://api.jquery.com/load/

Kind regards, mtness.

pashine Jul 10 2010

I am presently redesign a site and the navigation is using AJAX and jQuery and it’s beautiful. However, as well thought out development continues, AJAX has revealed several unexpected challenges. The navigation has a client-side animation and upon that action, it sends the user to the page selected. Great, you would think. Well, first, AJAX, which was added later in the development to accommodate this dual client and server-side action without page reload has; limited the URL like Twitter, Gmail, etc. to the same URL, never changing (unless you “hack” with the “history feature” which includes # which acts like an anchor tag, letting the everything after appear as a real URL (eg. http://www.mysite.com/#aboutus.html). Without the hack, NO about us. SEO and Google has many issues with crawling your site, collecting data and ranking you…more hacks needed. Back button doesn’t work…another hack and several more. The greatest issue is make “the full loop”. This means as you drill down within the site and come upon a “soft-link” or any other link that takes you out of the current navigated section, the content replies fine and take you to the new main area of the site, but the jQuery/AJAX navigation should be in a different “state”…a different main, sub, etc. place in the header navigation. The animation doesn’t need to replay, but the 360 degree loop needs to be closed and tell the server that you are in a NEW area. AJAX causes issue with this. Now take all of this and place it within WordPress? Eric, your thoughts would be welcomed…as well as anyone else. TY

Eric Rowell Jul 19 2010

Hey pashine, I know exactly the problem you’re speaking of – the infamous AJAX vs. back button problem.

Whenever you press the back button, the browser is returning the user to the last posted page. The problem with this, however, is that if you’re using AJAX, the state of the webpage changes without posting, so when you make a lot of changes to a particular page, navigate to another page, and then press the back button, the previous state is lost.

I’ve found that the best solution to this problem is to force the browser to remember the webpage’s state by posting the current webpage before redirecting the user to another page. It would work like this. The user accesses an AJAX rich page, and changes the state of the webpage. When the user clicks on a link to go to another page, you should send the user to the current page with parameters, like http://www.mysite.com/page.php?var1=a&var2=b. Next, using body onload, direct the user to the url that they originally clicked on. When the user presses the back button, the last state of the previous web page will be restored!

Good luck!

very good article, congratulations…

akeanant Nov 27 2010

Very nice solution.

Shahid Karimi Dec 21 2010

Oh, I will use Ajax to cook foot in the kitchen as I m alone in the city. Thank you Ajax

Thirmal Reddy N Jan 05 2011

Really nice one. Thanks.

Deepak Madheshiya Feb 02 2011

Very very good articles….Each and every step is explained very clearly…..! Thanks alot

Gurvinder Singh Mar 14 2011

Great article……….

It’s a great article for freshers. Thank you

Sivareddy B May 03 2011

very nice..Thank Q very much

The jQuery call used in the article can be shortened to

$.post(“some.php”, “name=John&location=Boston”, function(msg)
{
alert( “Data Saved: ” + msg );
});

$.Ajax({
type: “POST”,
url: “some.php”,
data: “name=John&location=Boston”,
success: function(msg){
alert( “Data Saved: ” + msg );
}
})

It’s a great article. Thank you

Caleb Hicks Aug 13 2011

Hi, nice theme created.

Great article and a great way of explaining it.

This comment section is closed. Please contact us if you have important new information about this post.

Advertisements
Partners