jQuery AJAX Load

jQuery AJAX load() Method

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

It loads data from a server and instantly puts the returned data into the selected element.

This is the easiest way to fetch text or HTML files remotely.


The load() Method Syntax

The standard syntax is: $(selector).load(URL, data, callback);

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

The optional data parameter specifies a set of querystring key/value pairs to send along with the request.

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


Basic load() Example

Imagine you have a text file named demo_test.txt located on the same server.

The file simply contains the text: <h2>jQuery AJAX is Amazing!</h2>.

We can load this content directly into a <div> using the load() method.

The load() Example:

$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});

Loading Specific Parts of a File

The load() method allows you to fetch only a specific part of a document.

You can append a jQuery selector to the URL parameter.

For example, you can load just the element with the ID p1 from demo_test.txt.

Loading Specific Elements:

$(document).ready(function(){
  $("button").click(function(){
    // Notice the space before #p1
    $("#div1").load("demo_test.txt #p1");
  });
});

This is incredibly useful if you only want to scrape a small piece of data from a large webpage.


The Callback Parameter

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

The callback function can take three different parameters:


Callback Function Example

Here is how you can trigger an alert based on whether the load was successful or failed.

Callback 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);
  });
});

This helps you debug missing files or server crashes gracefully!


Exercise 1 of 1

?

What does the load() method do in jQuery?