jQuery Load


The load() method


The jQuery load() method fetches data from a server and inserts it into the selected element's HTML. This approach is an easy way to load data from a web server asynchronously. The following is the method's basic syntax:



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



The following are the parameters of the load() method:

  • The URL of the file you want to load is specified by the appropriate URL parameter.
  • The optional data parameter defines a query string (i.e. key/value pairs) that is sent along with the request to the web server.
  • The complete parameter is essentially a callback function that is called when the request is over.

Let's bring this technique to the test. Make a new HTML file called "test-content.html" and save it to your web server. Now copy and paste the HTML code below into this file:



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



Now, build a new HTML file called "load-demo.html" and save it in the same place as the previous one. Now type the following HTML code into the box:



<!DOCTYPE html>
<html>
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
      $("#box").load("test-content.html");
  });
});
</script>
</head>
<body>
    
<div id="box">
<p>To load new content inside div "box", click on the following button...</p>
</div>
<button type="button">Load Content</button>

</body>
</html>

Live Demo!


Finally, press the Load Content button on this page in your browser. The HTML content of the "test-content.html" file has replaced the DIV box's content.