jQuery load(), it is a very simple method but powerful AJAX method. The load() method is used to load data from server and puts the returned value into selected element without loading the entire page. This jQuery load method has 3 parameters, including URL, data and Callback.

Syntax for load()

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

URL parameter is to metion the url that need to load. Likewise, data parameter is helps to specify a colletion of querystring value pairs to send with the request. Finally callback is an optional one, which is the name of a funcion to be executed after the load() method is completed.

Example: 1

$(“#div”).load(“demo_ld.txt”);

The above example loads the data of the file “demo_ld.txt” into a specific <div> element.

Example: 2

$(“#div”).load(“demo_ld.txt #p”);

This will loads the content of the element wit id=”p” in the file into a particular div element.

The optional callback parameter also has different parameters, such as responseTxt, statusTxt and xhr.

Example: 3
$(“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);
  });
});
Complete example for load() method
<head> 
        <script src= 
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
        <script> 
            $(document).ready(function(){ 
                $("button").click(function(){ 
                    $("#div_content").load("gfg.txt"); 
                }); 
            }); 
        </script> 
        <style> 
            body { 
                text-align: center; 
            } 
            .gfg { 
                font-size:40px; 
                font-weight: bold; 
                color: green; 
            } 
            .geeks { 
                font-size:17px; 
                color: black; 
            } 
            #div_content { 
                font-size: 40px; 
                font-weight: bold; 
                color: green; 
            } 
        </style> 
    </head> 
    <body> 
        <div id="div_content"> 
            <div class = "gfg">GeeksforGeeks</div> 
            <div class = "geeks">A computer science portal for geeks</div> 
        </div> 
        <button>Change Content</button> 
    </body>

Leave a Reply

Your email address will not be published. Required fields are marked *