jQuery load() Method

jQuery load() method is a powerful AJAX method used for loading data asynchronously. The load() method loads HTML or text content from a server and added into a DOM element. Syntax:

$(selector).load(URL,data,callback);
Here is "demo_test.txt" file content:
<h2>jQuery and AJAX is FUN!!!</h2>  
<p id="p1">This is some text in a paragraph.</p>

Example:

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script>  
$(document).ready(function(){  
    $("button").click(function(){  
        $("#div1").load("demo_test.txt");  
    });  
});  
</script>  
</head>  
<body>  
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>  
<button>Get External Content</button>   
</body>  
</html>
Try Now The callback optional parameter is the name of a function to be executed when load() method is completed. The parameter of callback is different: responseTxt: If the call succeeds then it contains the resulting content. statusTxt: statusTxt is used to contain the status of the call. xhr: xhr is used to contain the XMLHttpRequest object. In the following example if the load() method completes then an alert box displays. It displays "External content loaded successfully!" message if the load() method succeeds and if it fails then it displays an error message.

Example:

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script>  
$(document).ready(function(){  
    $("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);  
        });  
    });  
});  
</script>  
</head>  
<body>  
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>  
<button>Get External Content</button>  
</body>  
</html>
Try Now 



ADVERTISEMENT
ADVERTISEMENT