jQuery load() Method
The load() method is one of jQuery’s simplest and most effective ways to work with AJAX. It allows you to fetch content from a server and inject it directly into a selected HTML element—all without refreshing the page.
Syntax
$(selector).load(URL, data, callback);
- URL (required) – The file or endpoint you want to load data from
- data (optional) – Key/value pairs to send along with the request (like query strings)
- callback (optional) – A function to run once the request is completed
Example 1: Load Full External File into a <div>
If you have a file called demo_test.txt with the following content:
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
You can load it into a <div> with this code:
$("#div1").load("demo_test.txt");
Example 2:Load a Specific Element from the File
You can also load only a specific part of a file by adding a selector to the URL. For example, to load just the <p> with id="p1":
$("#div1").load("demo_test.txt #p1");
Example 3: Using a Callback Function
You can pass a callback to handle what happens after the content is loaded. This can include success or error handling.
$("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);
});
});
Callback Parameters:
- responseTxt – The loaded HTML content (if successful)
- statusTxt – The status of the request ("success" or "error")
- xhr – The raw XMLHttpRequest object
The load() method is perfect for quickly bringing in external data, content fragments, or even server-generated HTML into your pages without writing much code.