jQuery Ajax Load

jQuery load() Method

The jQuery load() method retrieves data from the server and inserts the returned HTML into the selected element. This method simplifies the asynchronous loading of data from a web server.

$(selector).load(URL, data, complete);

The parameters of the load() method have the following meanings:

  • The required URL parameter specifies the location of the file to load.
  • The optional data parameter specifies a set of query string parameters (key/value pairs) sent to the web server with the request.
  • The optional complete parameter is a callback function executed when the request finishes. The callback runs once for each selected element.

Let's apply this method practically. Create an empty HTML file named "test-content.html" and save it on your web server. Then, place the following HTML code inside this file:

<h1>Simple Ajax Demo</h1>
<p id="hint">This is a simple example of Ajax loading.</p>
<p><img src="sky.jpg" alt="Cloudy Sky"></p>

Now, create another HTML file named "load-demo.html" and save it in the same location where you saved the previous file. Then, insert the following HTML code into "load-demo.html":

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery load() Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#box").load("test-content.html");
    });
});
</script>
</head>
<body>
    <div id="box">
        <h2>Click button to load new content inside DIV box</h2>
    </div>
    <button type="button">Load Content</button>
</body>
</html>

Finally, open this page in your browser and click the "Load Content" button. You'll observe that the content inside the DIV box gets replaced by the HTML content fetched from the "test-content.html" file.

Tip: To test this Ajax example, you need to host the HTML files on a web server. You can set up a local web server on your PC by installing WampServer or XAMPP. Ensure you access the demo file using "http://" because Ajax operates via HTTP requests.

 

Note: Ajax requests can only be made to files that exist on the same web server serving the page from which the Ajax request originates. Requests cannot be made to external or remote servers due to security restrictions known as the same-origin policy.

Additionally, the callback function can accept three parameters: responseTxt, which contains the returned content if the request is successful; statusTxt, which indicates the status of the request (success or error); and jqXHR, which holds the XMLHttpRequest object.

Furthermore, the callback function can have three different parameters:

  • responseTxt — Contains the resulting content if the request succeeds.
  • statusTxt — Indicates the status of the request, such as success or error.
  • jqXHR — Holds the XMLHttpRequest object.

Here's an updated version of the previous example that displays either a success or error message to the user based on the request status.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery load() Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#box").load("test-content.html", function(responseTxt, statusTxt, jqXHR){
            if(statusTxt == "success"){
                alert("New content loaded successfully!");
            }
            if(statusTxt == "error"){
                alert("Error: " + jqXHR.status + " " + jqXHR.statusText);
            }
        });
    });
});
</script>
</head>
<body>
    <div id="box">
        <h2>Click button to load new content inside DIV box</h2>
    </div>
    <button type="button">Load Content</button>
</body>
</html>

Loading Page Fragments

The jQuery load() method also enables us to fetch specific portions of a document. This can be done by appending the url parameter with a space followed by a jQuery selector. Let's explore the following example for clarification.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery load() Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#box").load("test-content.html #hint");
    });
});
</script>
</head>
<body>
    <div id="box">
        <h2>Click button to load new content inside DIV box</h2>
    </div>
    <button type="button">Load Content</button>
</body>
</html>

The jQuery selector #hint in the url parameter (line no-10) specifies the portion of the "test-content.html" file that will be inserted into the DIV box. This selector targets an element with the ID attribute set to hint, which is defined as id="hint". Refer to the first example for clarity.