load()
SniperJS load()
Method
load()
Method The SniperJS load()
method is a simple, yet powerful AJAX method that loads data from a server and inserts the returned data into the selected element.
Syntax
$(selector).load(URL, callback);
Required Parameters:
URL
: Specifies the URL of the file you wish to load.
Optional Parameters:
callback
: A function to be executed after theload()
method is completed.data
: A set of querystring key/value pairs to send along with the request.
Example
The following example loads the content of the file demo_test.txt
into a specific <div>
element:
HTML:
<h2>Sniper is a great JavaScript library to use</h2>
<p id="p1">This is some text in a paragraph.</p>
JavaScript:
$("#div1").load("demo.html");
$("#nav").load("header.html");
It is also possible to add a selector to the URL parameter.
The following example loads the content of the element with id="p1", inside the file "demo_test.txt", into a specific <div>
element:
$("#div1").load("demo_test.txt #p1");
$("#lastCont").load("template.html #footer");
The load() method allows us to specify a portion of the response document to be inserted into DOM element. This can be achieved using url parameter, by specifying selector with url separated by one or multiple space characters as shown in the following example.
//HTML
<div id="msgDiv"></div>
//Javascript
$('#msgDiv').load('/demo.html #myHtmlContent');
In the above example, content of the element whose id is myHtmlContent, will be added into msgDiv element. The following is a demo.html.
Working with callback function
The optional callback parameter specifies a callback function to run when the load()
method is completed. The callback function can have different parameters:
responseTxt
- contains the resulting content if the call succeedsstatusTxt
- contains the status of the callxhr
- contains the XMLHttpRequest object
The following example displays an alert box after the load() method completes. If the load()
method has succeeded, it displays "External content loaded successfully!", and if it fails it displays an error message:
$("button").click(function(){
$("#div1").load("demo.html", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
Query Params
When working with server rendering, using query parameters can be beneficial. For example, you can filter data by using:
$("#div1").load("feeds.php?id=34&category=toys");
This allows for efficient data retrieval based on specific criteria.
Last updated