In a lot of my other posts I show sample code that makes heavy use of ajax calls and today I wanted to take a step back and explain what exactly are ajax requests, when you should use them, and how to get the job done. First, ajax stands for Asynchronous JavaScript and XML which may still be a bit too technical but essentially what it does is allow you to make a request to the server for data without having to refresh the page. Obviously this is a very useful tool to have no matter what you are doing on the web. No one likes to have to wait for the entire page to reload all of the images and content just because you clicked a button to show more data on a section of the page.
Ajax calls should be used anywhere you want to get data without doing a hard refresh. This can range from something small like updating a table every ten seconds automatically or to something complicated like automatic submission and verification of individual form fields. One way to leverage the asynchronous nature of these calls is to load your main html page that merely holds placeholder divs with no content in them. Once that very light page is loaded you make a series of ajax requests to the server to fill in those various portions of the page. This gives the user a very quick response time so they see that your site is up and running and other, more intensive, portions of the site can be loaded when they get processed. Ever gone to a site and after the page has loaded there is still a spinning wheel on some section of the page? That's an ajax call running and they have let you know something will be there soon.
To make an ajax call using jQuery requires very little code but you need to understand the back and forth interaction to make sure you use and display the data correctly. An ajax call consists of the method call and a dictionary of parameters to be used. There are many optional ones but I will go over the more commonly used ones.
$("#blogForm").submit(function(e){
$.ajax({
url: 'savepost/',
type: 'POST',
data: $(this).serialize(),
error: function(data) {
alert("An error has occurred. " + data);
},
success: function(data) {
$("#postsTable tr:last").after(data);
},
});
});
In the example above we are submitting a form and then adding the returned html data to the table. This allows us to dynamically add to an HTML table without needing to refresh the page every time. Let's go through each of the parameters in the dictionary that is passed with the ajax request.
Ajax calls are crazy powerful and unbelievably useful for nearly aspect of web development. Play around with it and make your websites better. There are a lot of ajax parameters you can use with your jQuery call. I only touched on a few of the more important ones here.