Using Ajax And jQuery To Load Dynamic Content In A Website

January 26, 2011 — Loading dynamic content into a website with Ajax is much simpler with jQuery, but there are also many methods to achieve similar effects. This article explains the use and difference between .load(), .get() and .post(), and .ajax() functions.

basic jQuery ajax overview

To dynamically load content in a website with Ajax, you have three basic options:

.load()
Load a webpage from your server, and place the output into an element on the page.
.get() and .post()
Load a webpage from your server, and decide what to do with the output. Additionally, you have the option to pass variables.
.ajax()
Load a webpage from your server, and decide what to do with the output. Additionally, you have several advanced options.

.load()

This is the simplest method for loading dynamic content in a website. Simply call the element you want to display the webpage inside, like a <div> tag, and then tell which page you want to load:

This will load the body content of pagetoload.html into #myDynamicDiv
  1. $('#MyDynamicDiv').load('mypages/pagetoload.html');


There a few extra options with this function, such as specific parts of a page to load and using variables. Read more about these advanced options. Or continue to the $.get() and $.post() functions that focus more on the result of the webpage loaded.

.get() and .post()

Both $.get() and $.post() are advanced functions for loading pages when your goal may not be to display the page (though you can if you want). In it's simplest use, it merely loads a page behind-the-scenes, and doesn't tell you or the user anything. This may be useful if you want a PHP page to quietly save information to a database:

This will process pagetoload.html, and do nothing else
  1. $.get('pagetoload.php');


In the above example, we've used $.get(), but we could also use $.post(). The difference is that $.get() will send data that PHP would retrieve with $_GET and $.post() would send data to be retrieved by $_POST. This is just like when a <form> sends data to another page, you would set the action equal to "GET" or "POST".

All of these will process pagetoload.html, and pass the variables "item" and "location"
  1. $.get('pagetoload.php', 'item=519&location=currentpage.html'); // For $.get() only
  1. $.get('pagetoload.php', {item: '519', location: 'currentpage.php'});
  1. $.get('pagetoload.php', {item: itemID, location: currentPage});


Again, in the above example, we've used $.get(), but we could also use $.post(). There are also other ways to pass data, and to perform functions after the page is processed, including loading the requested page into the current page just like .load() does. Read more about these advanced paramaters or skip directly to the $.ajax() function, which allows everything the $.get() and $.post() functions do, and more.

.ajax()

The $.ajax() function allows expert settings for complete control over your dynamic content. The single parameter for this function is an array with 20+ key/values that can be set. Fortunately, all of them are optional. So, in it's simplest form, you can simply write:

This will process the current page, and do nothing else
  1. $.ajax()


This doesn't seem to be very useful, but thats were the array parameter comes in, to customize your ajax request just like you want it. To start with, lets replicate the basic $.get() example using $.ajax(), like this:

This will process pagetoload.php, and pass the variables "item" and "location"
  1. $.ajax({
  2.     url: 'pagetoload.php',
  3.     data: {item: itemID, location: currentPage}
  4. //  data: 'item='+itemID+'&location='+currentPage // Alternate syntax
  5. });


Notice the different syntax available for data. All values for the $.ajax() function keys you will be introduced to can use hard-coded data or variables. You may also notice that this code is longer than the .load() code, but still fails to notify us or the user of a change, and certainly doesn't load content into the current page. That's because we haven't provided a success value. The next section will show us how to provide a success value, and load content into the current page.

$.ajax() Success (the callback function)

A major feature of $.ajax() function is the "callback function". For a good introduction to the callback function, please read our intermediate tutorial on advanced uses of $.get() and $.post(). If you already understand callback functions, then let's get right to it. Your callback function should be typed as the value of the success key:

This will process pagetoload.html, and then alert us the page was successfully loaded
  1. $.ajax({
  2.     url: 'pagetoload.php',
  3.     success: function(){
  4.         alert('The page was loaded');
  5.     }
  6. });


All ajax functions discussed have been able to load content into the webpage. The function $.ajax() is no different. Simply pass the data parameter to the callback function, and use the data parameter within the function.

This will process pagetoload.html, load the content, and alert us the page was loaded
  1. $.ajax({
  2.     url: 'pagetoload.php',
  3.     success: function(data){
  4.         $('#myDynamicDiv').html(data); // Load data into a <div> as HTML
  5.         alert('The page was loaded!');
  6.     }
  7. });


Though the simpler functions we've already mentioned will get this job done more easily, there are situations where only $.ajax() can complete the task. To really understand the power of the function, one would need to explore all 20+ key/value pairs (i.e. options for the function). In the final section we'll a mention a few that might be useful.

.ajax() Optional Parameters

The following code will pass several parameters to the $.ajax() function, and offer a brief comment for each.


This will process pagetoload.html non-cache, send variables as GET type, and HTTP access authentication
  1. $.ajax({
  2.     url: 'pagetoload.php',
  3.     data: {item: '519'},
  4.     type: 'POST' // Default value 'GET' sends data via GET
  5.     cache: true // Alternate value false forces browser not to send cached page
  6.     async: true // Alternate value false pauses current page until action is complete
  7.     username: userVariable // Optional value for HTTP authentication
  8.     password: passVariable // Optional value for HTTP authentication
  9. });
cache:
Many browsers cache pages for faster loading. Set this to false to ensure $.ajax() loads the latest version of a page.
type:
This is where you can set data to be sent by GET or POST, giving $.ajax() the functionality of the simpler functions above.
async:
The term AJAX infers data is loaded asynchronously. Set this to false to pause the browser while the ajax request is processed.
username:
Provide a username to websites protected by access authentication (the browser prompts you for login credentials).
password:
Provide a password to websites protected by access authentication (the browser prompts you for login credentials).

more about jQuery ajax

There are other ajax-related functions not covered by this tutorial. And above was only a brief sampling of all the parameters the $.ajax() function can accept. For more information, please refer to the jQuery API.

Add a Comment

Comments

Posted Subject Comment
paul
November 10, 2011
Cartwright Does any one know how to get this working with textarea field rather that input field
Author
August 30, 2011
In reply to: Ravi
library and version.
jQuery v1.4.4
Our website and this code runs on jQuery 1.4.4
Author
August 30, 2011
In reply to: Tariq
Could not get ross domain site data
Cross-domain not allowed
jQuery's ajax implementation does not support cross-domain calls. This quote is directly from their website:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
Ravi
August 23, 2011
library and version. what libraries and version did you use here
Author
July 02, 2011
In reply to: Marco
I can user this
Yes, you may
You are welcome to use this ajax jquery example for your website. If you are kind enough we would appreciate a link back to our website.
Marco
July 01, 2011
I can user this I have a website: http://www.maskay. Can I use this ajax in my website? have a example of jQuery?
Author
June 23, 2011
In reply to: Tariq
Could not get ross domain site data
Do the domains share a server?
Normally this is a server related issue. Are the domains on the same server? Is the content dynamic being pulled from MySQL?

Edit: See second reply (August 30, 2011) to this post.
Tariq
June 23, 2011
Could not get ross domain s... I have try my best to get cross domain data using ajax jquery