Introducing the .load() method

The load() method is the simplest of all JQuery methods. By and large, we simply pass it a URL, which it will asynchronously load the content of, and then insert the content into each of the selected elements, or replacing any content that is already there.

.load(url, data, callback)

Aside from url, the load() method accepts two optional arguments.

Parameters Type Description
url String URL of Server Resource to which the request is sent. If you only want to display a portion of the loaded document, add a space to the URL and follow it with a JQuery selector. $('#div1').load(' #article');
data String or Object Data to append to the URL or to send along with the request. If you pass a string, it is appended to the URL (after a ? or &, as needed). If you pass an object, it is converted to a string of ampersand-separated name=value pairs and sent along with the request. If specified as an object, the request is made using the POST method. If omitted or specified as a string, the GET method is used.
callback Function A callback function that will be invoked when the Ajax request completes. If you don't specify any data, you can pass this callback function as the second argument.

With the JQuery object method .load(), the example we have seen in Fetch Data from Server can be greatly simplified to a line of code.


function GetData() {
    // 1. Instantiate XHR - Start 
var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); else if (window.ActiveXObject) xhr = new ActiveXObject("Msxml2.XMLHTTP"); else throw new Error("Ajax is not supported by your browser"); // 1. Instantiate XHR - End // 2. Handle Response from Server - Start xhr.onreadystatechange = function () { if (xhr.readyState < 4) document.getElementById('div1').innerHTML = "Loading..."; else if (xhr.readyState === 4) { if (xhr.status == 200 && xhr.status < 300) document.getElementById('div1').innerHTML = xhr.responseText; } } // 2. Handle Response from Server - End // 3. Specify your action, location and Send to the server - Start'GET', ''); xhr.send(null); // 3. Specify your action, location and Send to the server - End } </script>


function GetData() {

Now, just click the "Get Data" button and JQuery's load() method will fetch the result from server and populate into div1.