A guide to Ajax Interactions with jQuery

The fantastic jQuery library revolutionized the way javascript is being written around the globe. It's been globally acclaimed and adopted, resulting in an award for best open source project in the end of 2009.

In this article, we are going to see how we can use the power of this library to create your own Ajax request effortlessly, to make pages communicate in a user friendly way. Thank you jQuery team, the days of javascript darkness are over!

Thank You for Downloading

I'm glad that you found my work useful. If you did, it might help some other people too. So why not helping me spread the word with a tweet? You could also buy me a coffee to thank me for my code and explanations if you prefer ;).
I hope you'll enjoy your download. Regards. Jeremy.

How to setup

When to use Ajax?

Sometimes, but more particularly in rich interfaces, it is needed to send or receive some extra bit of information without reloading or changing the page. For example, when you want a user to send a comment to another one via a form, but you don't want the whole page to be refreshed when he presses the submit button. In such situations, Ajax allows us to send data to a hidden page, and to input the result back to the original page that the user is looking at without the need to refresh. This flexibility opens a wide new horizon of possibilities such as behind the scene seamless database interaction, without the user being annoyed by loading times and page reloads. This asynchronous behaviour makes it a powerful and popular technology worth considering when implementing interactive interfaces.

jQuery Events: how to trigger an Ajax request?

Now that we now that thanks to Ajax we can exchange information between some pages after a page load, we'll have a look at how we can start this process thanks to a bit of client side scripting. In other words, how it is possible to create an Ajax request from a simple jQuery script. jQuery being a javascript framework, you can use any sort of javascript Event to trigger your request, the most common ones being click (when you click on a particular element), or mouseover (when you over it with you mouse). But you can really use any event that suits you best. As a result, the code to prepare your own event could look like:
  1. jQuery(document).ready(function(){
  3. $("a#myclicktrigger").click(function(){ //Click event
  4. //Do Some Ajax Here when the link #myclicktrigger is clicked
  5. });
  7. $("div#myovertrigger").mouseover(function(){ //Mouse Over event
  8. //Do Some Other Ajax There when the div #myovertrigger is mouseovered
  9. });
  11. });

The way jQuery creates requests

Before jQuery, it involved quite a few lines of code to establish a decent Ajax connection between two pages, but jQuery makes it so easy right now, that you can enjoy all the benefits of the technology, without the setup headache. Indeed, the Ajax methods are all part of the jQuery core directly. You just need to figure out which one you need to use according to what you want to achieve. The following 6 methods are available: jQuery.Ajax()
  1. //jQuery.ajax( options )
  2. //Loads a remote page using an HTTP request.
  4. //ex:
  5. $.ajax({
  6. type: "POST", //type
  7. url: "test.php", //url
  8. data: "id=138&price=200", //data
  9. success: function(resultfrompage){ alert(resultfrompage); } //callback
  10. });
  11. //This will POST the values to the page test.php and alert the result
The jQuery.Ajax() method is the lowest form of Ajax request you can do with jQuery. You specify a set of options to make it work and it will create an HTTP request to load a remote page for you. Those options are the type of the request(GET or POST), the url you want to load (ex: mypage.php), and you can even specify a query string of data (ex: id=138&price=200). As we said, it loads an entire page along with its headers and everything, so it is not the optimal solution. Consider it only if you need all those extra pieces that it will return, otherwise you should consider another Ajax method. load()
  1. //load( url, data, callback )
  2. //Loads HTML from a remote file and inject it into the DOM.
  4. //ex:
  5. $("#mycontainer").load("remotecontent.html");
  6. //This will get the content of the file remotecontent.html
  7. //and inject it into the div#mycontainer
The load() method is more interesting. It works a bit differently. You specify a container in your page such as a div, and the load method will get the content of a given remote page, and inject it inside this container. Like the jQuery.Ajax() method, you can specify in the options a url (remotecontent.html), some data, and a callback function.   jQuery.get()
  1. //jQuery.get( url, data, callback, type )
  2. //Loads a remote page using an HTTP GET request.
  4. //ex:
  5. $.get(
  6. "mypage.php", //url
  7. {firstname:"jeremy",lastname:"desvaux"}, //array of data
  8. function(returneddata){ //callback
  9. alert(returneddata);
  10. }
  11. )};
  12. //This will send a get request to the specified page, and alert the result
I would say that the jQuery.get() method is with the jQuery.post() the most interesting kind of Ajax request you can get. The principle is very easy, you specify a url and some data, and the $.get method sends the corresponding GET request and brings you the results back, so you can interpret them with a callback function. It is easy to use and gives you a lot of possibilities like getting information on a product for example, and output it to a user without leaving the page he is on. It is definitely a method to privilege. jQuery.getJSON()
  1. //jQuery.getJSON( url, data, callback )
  2. //Loads JSON data using an HTTP GET request.
  4. //ex:
  5. "mypage.php", //url
  6. {firstname:"jeremy",lastname:"desvaux"}, //array of data
  7. function(returneddata){ //callback
  8. $.each(data.items, function(i,item){
  9. alert(item.firstname+" "+item.lastname);
  10. });
  11. }
  12. )};
The jQuery.getJSON() method is derived from the jQuery.get() one but is to be used in a very specific case, which is, as its name implies, when you want to get some JSON data via Ajax. JSON is an efficient way to get a well structured set of data quickly into a javascript script. It becomes a good structure choice when you want to exchange some data between php and jQuery as both languages propose some native functions to work with it. To summarize, you send a getJSON request to a remote page, which uses those data and returns a JSON result. This JSON markup, which is often lighter than its html equivalent, is then loaded and interpreted inside the Query script. jQuery.getScript()
  1. //jQuery.getScript( url, callback )
  2. //Loads and executes a JavaScript file using an HTTP GET request.
  4. //ex:
  5. $.getScript("test.js", function(){
  6. alert("Script loaded and executed.");
  7. });
  8. //Loads the script of your choice, specified by its url, then executes it.
The jQuery.getScript() method is useful if you want to load an extra script asynchronously. For example, if you need a plugin on a certain page and you don't have the plugin script on your server, you can get it from a Content Delivery Network like google thanks to the getScript method. You can also use this method to get a script for a particular behaviour when a particular event appends without loading the script by default. For example, you could load the FancyBox script only when you click on a trigger link, thus saving loading for nothing it if you don't need it. jQuery.post()
  1. //jQuery.post( url, data, callback, type )
  2. //Load a remote page using an HTTP POST request.
  4. //ex:
  5. $.post(
  6. "mypage.php",
  7. {firstname:"jeremy",lastname:"desvaux"},
  8. function(data){
  9. alert("Data Loaded: " + data);}
  10. });
  11. //This will post the data firstname and lastname to the page mypage.php
  12. //and alert the results.
The jQuery.post() method is the one I use the most with jQuery.get(). They work in a similar way, the only difference being as you can guess the type of request that is created in the end (post vs get). This very handy method allows you to easily post method to a remote page via Ajax like they were sent from a form. The possibilities are then huge. you can for example send comments remotely, edit data from a database and so on without reloading the page. It is much better from a user experience point of view. Now that we have reviewed the different methods available to create Ajax request on the client side, we'll now analyse what can be done on the server side pages that are going to receive those data.

Request processing on the server side

What is really interesting with Ajax on the server side, is that you can write a script that handles data exactly like you would do if there were no Ajax involved. There is absolutely no difference. You can use the $_GET and $_POST global arrays to retrieve your data as you would normally do. Yes really ! Let's have a look at the following example:
  1. //On the client side, you create your request
  2. jQuery(document).ready(function(){
  4. $("a#myclicktrigger").click(function(){ //Click event
  5. //Will post the data to mypage.php when the link #myclicktrigger is clicked
  6. $.post(
  7. "mypage.php",
  8. {firstname:"jeremy",lastname:"desvaux"},
  9. function(data){
  10. alert("Data Loaded: " + data);}
  11. });
  12. });
  14. });
  1. //On the server side, you handle your data:
  2. //So mypage.php could look like:
  3. <?php
  4. $firstname = htmlentities($_POST&#91;"firstname"&#93;,ENT_QUOTES);
  5. $lastname = htmlentities($_POST&#91;"lastname"&#93;,ENT_QUOTES);
  6. echo $firstname." ".$lastname;
  7. //Like you would normally do.
  8. ?>
If we analyse the previous lines, we can see that we create an Ajax post request between the lines 6 and 11. The request will send the data firstname and lastname to the page mypage.php as soon as the link #myclicktrigger is clicked. Then, on the server side, we access the usual $_POST array to work with our posted data. It is as simple as that to work with Ajax requests on the server side.

Returning the response to the user

So far in the process, we've learnt how to create an Ajax request, send it to the server side, and work with the data there. But because it is all Ajax, meaning happening behind the scene, the user won't see what is going on behind the page he is looking at, that's why when you are working with Ajax, it is very important to pay attention to the feedback you'll return to him. In order to do this, I would like to draw your attention on the fact that every jQuery Ajax method listed above can have a callback function. It is this callback function that you can use to retrieve the result of your Ajax query. How do you do that? Well just keep in mind for the moment that anything that you display on your server side page, will be sent back to the callback function, because this is what makes the connection. For example, if you take the previous piece of code, at line 6 in mypage.php , you'll see echo $firstname." ".$lastname; And in the javascript, line 9, you have the callback function that takes a parameter data and alerts it. Based on what we've just seen, the callback function will receive from mypage.php the echoed string Jeremy Desvaux and that's what it will alert. Based on this principle you can now start implementing much more complex interactions between client and server side scripts. If I go back to the example of a user sending a comment to someone else, then you can submit his comment via Ajax without changing the page. The Ajax request will send the data to a page that will process the comment and save it to the database. This page will then return the result of the transaction back to the jQuery script where it will be interpreted and inserted in the dom to notify the user. You can find a full working example of an Ajax comment submission on its dedicated page.


This ends our review of the Ajax interaction process, it can be summarized as 5 different steps: Prepare a request with one of the 6 available methods, send it when particular event is fired, work with the data on the server side, and finally send the result back to the javascript and the user. Like we said before, the possibilities are not limited by technical difficulties, but by your own creativity now. Let me know if you are struggling with an Ajax situation. I will try to help you out and will update the post with the interesting ones as examples. Happy Ajax coding!
  1. jQuery(document).ready(function(){
  2. $("a#myclicktrigger").click(function(){ //Click event
  3. //Do Some Ajax Here when the link #myclicktrigger is clicked
  4. });
  5. $("div#myovertrigger").mouseover(function(){ //Mouse Over event
  6. //Do Some Other Ajax There when the div #myovertrigger is mouseovered
  7. });
  8. });

2 Responses to A guide to Ajax Interactions with jQuery

  1. Hello, This is a good example. But please can You fix the code so the ajax reqest - message do not duplicate itself when i click again the link ?
    It would be nice if the script refresh the content just in one place when i click again on the link

    Thanks for Your work!

  2. nice tutorial about jquery ajax. i am new to jquery ajax. if you give examples then it will be good for new users. please post more tutorials . i love to read ur blogs..

Leave a Reply to krushna Cancel reply

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

Other Useful Resources

How to integrate your instagram pictures with php illustration

Ever looked for a straightforward way to integrate you instagram pictures on your website? Without a plugin nor an iframe? Well this article featured on the NOE interactive's blog presents how you can do so with PHP.

It's a neat and simple solution that uses the instagram's API to get a particular users' latest pictures, and then display them in a ul list.

It is accessible to most developers as it is a "personalize, copy and paste" kind of solution. Just two steps are required, configuration, and implementation.

In this article featured on NOE interactive, you'll learn how you can install the solution on your website. There's a complete step by step guide as well as a demonstration. If you wish to download the solution, it's also hosted on Github.

Read more
Creating a simple image gallery with PHP & jQuery illustration

An image gallery is a very common feature for a website to have. It is an efficient way to nicely present a set of pictures. With the increasing popularity of JavaScript plugin, image galleries are nowadays implemented with rich features, effects, and transitions, in order to emphasize the given content.

When you wish to create a picture gallery, there are several steps involved in the process. In this tutorial, we will see how you can set everything up, and then add, remove, or edit pictures in your gallery, in a simple and dynamic manner. Finally, we will explain how we can setup the jQuery lightbox plugin in order to work with our pictures.

What are the benefits of this solution? This methods is sooo easy to setup, but still achieves quite a lot. Little efforts, great rewards. You only have to put your images in a folder, and give that folder path to the class. You also tell the class how big you want your pictures to be, and it handles all the hard work for you. Just by calling a method, you can see your gallery on the page. So if you are looking for a fast and convenient way to put an image gallery on a site, read on.

Read more
jQuery FancyBox plugin illustration

The FancyBox is one of the plugin that I like the most. It's so easy to use and renders really nicely, especially with images. It's a Mac like zooming tool that you can customize quite well and really looks amazing. Source and © Janis Skarnelis

Read more
@jeremypetrequin Ok tu build spécifiquement ce fichier scss pour avoir un fichier css que tu peux charger pour ton bloc en BO donc. Merci.22 May / 14:21