jQuery Tutorial
jQuery Introduction jQuery Getting Started jQuery Syntax jQuery Selectors jQuery Events
jQuery Effects
jQuery Hide/Show jQuery Fade jQuery Slide jQuery Animation jQuery stop() jQuery Callback jQuery Chaining
jQuery Manipulation
jQuery Get/Set jQuery Add jQuery Remove jQuery CSS Classes jQuery css() jQuery Dimensions
jQuery Traversing
jQuery Traversing jQuery Ancestors jQuery Descendants jQuery Siblings jQuery Filtering
jQuery AJAX
jQuery AJAX Intro jQuery Load jQuery Get/Post jQuery AJAX Events
jQuery Misc
jQuery noConflict() jQuery Filters
jQuery References
jQuery Reference jQuery Selectors jQuery Events jQuery Effects jQuery HTML/CSS jQuery Traversing jQuery AJAX jQuery Miscellaneous jQuery Properties

jQuery - AJAX load() Method

The jQuery load() method is a simple, but powerful AJAX method.


jQuery load() Method

The jQuery load() method loads data from the server and place the returned HTML into the selected element.

This method provides a simple way to load data asynchronous from a web server.

Here is the syntax for load() method:

$(selector).load(URL, data, callback)

Parameters:

  • URL - Specifies the URL you wish to request
  • data - (Optional) Specifies a plain object or string that is send to the server along with the request
  • callback - (Optional) Specifies a callback function that is executed after the load() method is completed

The following example loads the content of the ajax_intro.txt file into a DIV element:

Run code

The following example loads the ajax_post.php page, send some additional data along:

Run code

Here is how the PHP file looks like ("ajax_post.php"):

<?php
echo "<p>Hello ".$_POST['fname']." ".$_POST['lname'].", How are u doing?</p>";
?>

Request Method: The POST method is used if data is provided as an object; otherwise, GET is assumed.



Loading Page using Callback

The optional callback parameter specifies a callback function to run when the load() method is completed.

The callback function can have different parameters:

  • response - contains the result data from the request
  • status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")
  • xhr - contains the XMLHttpRequest object

The following example loads the ajax_post.php page, send some additional data along and alert status message:

Run code

The following example displays a notice if the Ajax request encounters an error:

Run code

Loading Page Fragments

The jQuery load() method also allows us to fetch only a portion of the document.

This is simply achieved by appending the url parameter with a space followed by a jQuery selector.

The following example loads the content of the element with id="table", inside the file "ajax_load.html", into a DIV element:

Run code

jQuery AJAX Reference

For a complete AJAX methods reference, visit our jQuery AJAX Reference.