HTTP is a stateless protocol Whenever user interacts with a webpage and perform some action a new request is generated and sent to the server. In return server returns markup for the webpage. However, size of a webpage can be very huge and user might want to update only a small part of webpage. In such cases, it is not a good idea to reload whole page. Here Ajax can be handy as it allows only partial page upload saving huge amount of data transfer between client and server.
JQuery uses load() function to interact with the server for data retrieval. The load() function sends request to the server and adds retrieved data to the element. It takes three parameters: url, data, and callback. The url is the file from which the load function retrieves data. This file is located on the server. The data consist of optional key-value pairs query string pairs sent to the server. Finally, callback function is the function that executes when load function completes its execution. Take a look at following example.
First create a file named “paracontent.txt” and add the following content to this file.
This is the text loaded via
The load method will load the content from this file and will place it inside the paragraph element. The complete code for the webpage including JQuery Ajax call is shown below.
The above page contains a button and a paragraph with some random text. Clicking the button fires an event which is handled by JQuery click function. Inside the click function the load() function loads the content of “paracontent.txt” file and adds it to the paragraph element. After that the call back function executes which displays a message to the user in the alert box.