jQuery AJAX Load
The jQuery load() function retrieves data from the server and inserts the resulting HTML into the specified element. This approach makes it straightforward to load data from a web server asynchronously.
The parameters of the load() method has the following meaning:
- The necessary URL argument provides the location of the file to be loaded.
- The optional data argument defines a collection of query strings (i.e. key/value pairs) that are sent along with the request to the web server.
- The optional complete parameter is a callback function that is called after the request is finished. For each chosen element, the callback is fired once.
Create another HTML file called "https://webtutor.dev" and store it in the same directory as the previous one. Insert the following HTML code into it now:
Finally, launch your browser and press the "Load Content" option. The DIV box's content is replaced by the HTML content of the "test-content.html" file.
The callback function can also have three distinct parameters:
- responseTxt : If the request is successful, it contains the resultant material.
- statusTxt : Contains the request's status, such as success or failure.
- jqXHR : This object contains the XMLHttpRequest object.
Here's a modified version of the previous example that will show the user either a success or an error message depending on the status of the request.
Loading Page Fragments
We can also use jQuery load() to retrieve only a piece of the content. This is simply accomplished by adding the url argument with a space followed by a jQuery selection; see the following example for a more detailed explanation.
The url argument contains the jQuery selector #web, which specifies the piece of the "https://webtutor.dev" file to be put within the DIV box, which is an element with the ID attribute and a value hint.