The load() method is the simplest way to use AJAX with jQuery. It fetches
data from a server and places the returned data directly into the selected HTML
elements. No manual DOM update is required!
The standard syntax for the load() method is:
$(selector).load(URL, data, callback);
// Simple example: Load content from a text file into #div1
$("#btn").click(function() {
$("#div1").load("demo_test.txt");
});
One of the most powerful features of load() is the ability to load only a
**specific part** of a file. You can do this by adding a space after the URL, followed
by a jQuery selector.
// Loads only the element with id="p1" from the external file
$("#div1").load("demo_test.txt #p1");
The callback parameter allows you to run code after the content has been loaded. It provides three useful arguments:
responseTxt — Contains the result of the call if it succeeded.statusTxt — Contains the status of the call ("success" or "error").xhr — Contains the XMLHttpRequest object.$("button").click(function() {
$("#div1").load("demo_test.txt", function(response, status, xhr) {
if (status == "success") {
alert("External content loaded successfully!");
}
if (status == "error") {
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
});
You can use load() to keep your main HTML file small by loading modal
content or sidebars only when they are needed.
// Load a user's profile view into a modal on click
$(".view-profile").click(function() {
var userId = $(this).data("id");
$("#modal-body").load("profile.php?id=" + userId);
});
status == "error" check in the callback to provide user feedback if a
request fails.