In the last article we saw what Ajax is and how it works. We saw how Load method was used to asynchronously load data from any resource on the server without complete page load. There are other ways to get data asynchronously from server via Ajax. JQuery contains Ajax Get and Post method for such purposes. This article provides a brief introduction to both Get method.
The get() function in JQuery requests data from any particular source on the server. This resource can be a JSON object, a text document or virtually anything. The get() method uses HTTP get request to request data from a server. It is important to note that get method may also return already cached data. The get() method takes two arguments: first one is the URL of the resource you want to request from the server and the second parameter is the call back function. Take a look at following example.
First create a file “paracontent.txt” and add the following content to this file.
This is the text loaded via
The get() 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 get() call is shown below.
The above code contains a button and a paragraph. Button click fires an event. JQuery click event handler handles this event. Inside the event handler get function executes and retrieves data from a text file. JQuery factory function selects paragraph and sets the html of the paragraph to the data returned by the server. As a result, when user clicks the button, the content of the paragraph elements are updated asynchronously via Ajax.