Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery - AJAX load() method


May 07, 2021 jQuery


Table of contents


jQuery - AJAX load() method


jQuery load() method

The jQuery load() method is a simple but powerful AJAX method.

The load() method loads the data from the server and puts the returned data into the selected element.

Grammar:

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

The required URL parameter specifies the URL that you want to load.

The optional data parameter specifies a collection of query string keys/value pairs sent with the request.

The optional callback parameter is the name of the function executed after the load() method is completed.

This is the contents of the sample demo_test.txt ("I don't know"):

<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>

The following example loads the demo_test.txt of the file "called " into the specified element of the .lt;div>

$("#div1").load("demo_test.txt");

Try it out . . .

You can also add the jQuery selector to the URL parameter.

The following example loads demo_test.txt the contents of an element in the "id" file, id"p1", into the specified element:

$("#div1").load("demo_test.txt #p1");

Try it out . . .

The optional callback parameter specifies the callback function to be allowed when the load() method is complete. Callback functions can set different parameters:

The following example shows a prompt box when the load() method is complete. I f the load() method is successful, the "External content loaded successfully!" and, if it fails, an error message is displayed:

$("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);
});
});

Try it out . . .

Tip: In jQuery's load() method, the callback function is triggered as soon as the request completes, regardless of whether the AJAX request is successful or not.