The jQuery ajax load() method is a very simple and powerful jQuery AJAX method. It loads data from the server and place the returned HTML into the matched element.
Syntax:
1 | $(selector).load(URL[,data][,callback]); |
Three Parameters :
Url: Required. specifies the url which is to be load.
data: Optional. A set of query string key/value pairs to send along with the request.
callback:Optional. function to be executed after the load() method is completed.
This method is the simplest way to fetch data from the server. Most uses of the method is simple
1 | $( "#fellowcontent" ).load( "fellowtuts/test.html" ); |
Note: If no element is matched by the selector — in this case, if the document does not contain an element with id=”fellowcontent” — the Ajax request will not be sent.
It is also possible to add a jQuery selector to the URL parameter.
1 | $( "#fellowcontent" ).load( "fellowtuts/test.html#ajaxdiv" ); |
The above given example loads the content of the element with id=”ajaxdiv”, inside the file “test.html”, into a specific fellowcontent Id element.
With data
1 | $( "#fellowcontent" ).load( "fellowtuts/test.php",'id=2' ); |
The above given example loads the data from test.php and passing ‘id=2’ as a request parameter.
Callback Function
The optional callback parameter specifies a callback function to run when the load() method is completed and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
callback function without parameter
1 2 3 | $( "#fellowcontent" ).load( "fellowtuts/test.html", function() { alert( "Load was performed." ); }); |
The example given above displays an alert box after the load() method completes.
The callback function can have different optional parameters:
responseTxt – contains the resulting content if the call succeed
statusTxt – contains the status of the call
xhr – contains the XMLHttpRequest object
callback function with parameter
1 2 3 4 5 6 7 8 | $( "#fellowcontent" ).load( "fellowtuts/test.html", function(responseTxt,statusTxt,xhr) { if(statusTxt=="success") alert("Load was performed."); if(statusTxt=="error") alert("Error: Load failed"); }); |
The example given above displays an alert box after the load() method completes. If the load() method has succeed, it displays “Load was performed.”, and if it fails it displays an error message “Error: Load failed”.