jQuery
load()
method used to loads data from the server and place the returned data into the selected element. load()
method very useful and simple way to load data asynchronous from the web server.
What can we do jQuery with Ajax? jQuery provides a number of methods for Ajax Development. You can fetch .txt, .html, .xml document data using
GET
or POST
method.
Syntax
$(selector).load( URL, [ data ], [ callback(response, status, xhr) ] );
Parameter
- URL Required. This parameter specifies the URL of the file that you want to load.
- data Optional. This parameter specifies the set of data (JSON formatted data) that you send to the server along with the request.
- callback Optional. This parameter basically callback function, it will executed when the request completes.
- response This parameter contains the response data from the request.
- status This parameter contains the status of the request for example "success", "error", "timeout".
- xhr This parameter contains XMLHttpRequest object.
Example
$(document).ready(function(){ $("button").click(function(){ $("div").load("ajaxfile.txt"); }); });
Example Result
Example (with callback function)
$(document).ready(function(){ $("button").click(function(){ $("div").load("ajaxfile_load_params.html", function(response, status, xhr){ if(status == "success"){ alert("Success! File content loaded successfully!\nStatus: " + xhr.statusText); } if(status == "error"){ alert("Error: " + xhr.status + " " + xhr.statusText); } }); }); });
Example Result