jQuery - AJAX load() Method


jQuery load() Method

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

The load() method loads data from the server and places the retrieved data in the selected element.

Syntax:


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

Required URL parameter specifies the URL you wish to upload.

The optional data parameter specifies a querystring key set / pair number for shipping and request.

Optional call parameter is the name of the job to be performed after the load() method has been completed.

Here is the content of our example file:

"demo_test.txt":


<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>

The following example uploads the contents of the "demo_test.txt" file to the <div> section:


Example
$("#div1").load("demo_test.txt");

It is also possible to add a jQuery selector to the URL parameter.

The following example uploads element content with id = "p1", within the "demo_test.txt" file, in the <div> section:


Example
$("#div1").load("demo_test.txt #p1");

The optional dialing parameter specifies the callback function that will be activated once the load() method has been completed. The callback function can have different parameters:

  • responseTxt - contains the resulting content if the call succeeds
  • statusTxt - contains the status of the call
  • xhr - contains the XMLHttpRequest object

The following example illustrates the warning box after the loading() is complete. If the load() method is successful, it shows "External content loaded successfully!", And if it fails it shows an error message:


Example
$("button").click(function(){
  $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
    if(statusTxt == "success")
      alert("External content loaded successfully!");
    if(statusTxt == "error")
      alert("Error: " + xhr.status + ": " + xhr.statusText);
  });
});