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

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

Other Useful Resources

Using Composer and Satis to handle private php repositories illustration

Composer is an awesome and powerful tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them, and their respective dependencies for you. To make your own libraries or packages usable by composer users, you need to declare them towards composer. When the package is public, less steps are required. You could host your repository online on GitHub for example, then declare it towards the packagist.org index for example. When the repository is private, it's a bit trickier, and I spent some time figuring it out, so here's a little feedback on my attempts.

Read more
How to turn any jQuery plugin into a WordPress one illustration

WordPress and jQuery are both very famous for their plugins. In the case of jQuery, plugins allow developers to extend the library's capacities in order to create beautiful effects. In WordPress, they allow anyone to benefit from the work of others, as they come under the form of a module that you can easily activate from within the administration interface, and start using right away.

Creating one of those modules is not that difficult, but if you are not familiar with their syntax, it could end up being a headache. There are many jQuery plugins that have been transferred into a WordPress one already, but what can you do when it is not the case? How do you do when you have found the perfect jQuery plugin for your latest site, but it is not yet available as a WordPress plugin?

In this tutorial, we'll see how you can easily create a WordPress plugin from a jQuery one. We'll review what a jQuery, or a WordPress plugin is actually made of, so we'll find the elements they both have in common. From there, we'll show how it leads us to perform some simple operations to allow us to benefit from our jQuery plugins in a WordPress template.

Read more
How to easily integrate a PayPal Checkout with PHP illustration

PayPal is a renowned payment platform that allows you to accept online payments on your site, by taking care of all the money transactions for you. This transparency really is an appreciated quality that allows developers to integrate checkout solutions on merchant sites, by completely outsourcing the banking operations to PayPal.

Another good thing for developers is that the PayPal API is very versatile. It can be very simple if your needs are simple, or it can be very well customized to meet some more advanced needs such as complete shopping carts handling. On the other hand, I sometimes find this API not really user friendly as it works with forms, which fields are not always very intuitive. In other words, depending on the form you are building, you get a different service from PayPal.

In order to get a friendlier and also more generic solution, I wrote a PayPal manager in PHP. This tutorial will show you how you can benefit from this PHP class to integrate PayPal checkouts faster and in a much simpler way.

Read more
@MrYannoch @toosoonparis Congrats and keep up the good work!17 Sep / 10:26