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 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.
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.
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
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.
$(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 optional callback parameter specifies a function to run when the load() method completes.
The callback function can take three different parameters:
responseTxt - Contains the resulting content if the call succeeds.statusTxt - Contains the status of the call (e.g., "success" or "error").xhr - Contains the XMLHttpRequest object.Here is how you can trigger an alert based on whether the load was successful or failed.
$("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!
What does the load() method do in jQuery?