Easy Tutorial
❮ Html Before Css Position ❯

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 puts the returned data into the selected element.

Syntax:

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

The required URL parameter specifies the URL you wish to load.

The optional data parameter specifies a collection of query string key/value pairs to be sent along with the request.

The optional callback parameter is the name of a function to be executed once the load() method is completed.

Here is the content of the example file ("demo_test.txt"):

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

The following example will load the content of the file "demo_test.txt" into the specified <div> element:

Example

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

You can also add a jQuery selector to the URL parameter.

The following example loads the content of the element with id="p1" from the file "demo_test.txt" into the specified <div> element:

Example

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

The optional callback parameter specifies a callback function to be executed when the load() method is completed. The callback function can have different parameters:

-responseTxt - contains the result content if the call is successful

-statusTXT - contains the status of the call

-xhr - contains the XMLHttpRequest object

The following example will display an alert box after the load() method completes. If the load() method succeeds, 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);
  });
});
❮ Html Before Css Position ❯