GET Method
Learn about the get() AJAX method in jQuery along with an example.
We'll cover the following...
get() method
get() is a jQuery AJAX method that loads data from a server with the help of an HTTP GET request.
The syntax for the get() method is given below:
jQuery.get(URL, Data, Callback, Datatype)
The description of each parameter is as follows:
URL- the specific server address to which the HTTP GET request is made, along with the resource/web page required.Data- the information sent to the server via the request URL, usually in the form of appended key-value pairs.Callback- the function executed after the successful completion of the GET request. The callback function receives two arguments,dataandtextStatus.datacontains the response from the server in the specifiedDataType.textStatuscontains the status of the GET request: success, etc.DataType- the type of data expected from the server, which can be JSON, text, HTML, XML, or others.
📝 Note: In the
get()method,URLis a required parameter, whileCallback,Data, andDataTypeare optional parameters.
Example: Get current weather
Consider the example below. This web page displays the current weather when the button “GET weather” is clicked. The current weather is fetched from a server with the help of a GET request. We don’t want the entire web page to reload, so we use the AJAX get() method in jQuery.
Step 1: Getting data from the server
Start by requesting the data from the server using the get() method (lines 3-9). As discussed above, the get() method expects us to specify the URL, DataType, and the Callback function. The Data parameter is not required here because we are not transferring any data to the server.
- The specific
URLfor the server ishttps://5f28559af5d27e001612eebf.mockapi.io/weather/(line 3). - The
DataTypeof the expected response isJSON(line 9) with two fields,idandweather. - The
Callbackfunction receives two arguments: thedataobject of typeJSONand thestatusTextvariable specifying the status of the GET request (line 4). We generate an alert in the callback function (lines 5-7), displaying thedataobject fields andstatusTextmessage.
📝 Note: The example is for learning purposes only. The server returns a dummy weather value of
26in all cases.
Step 2: Adding data to the webpage
Next, display the requested data on the webpage. In the callback function, we use the text() method to update the text of the div element (line 5). The div text now contains the current weather extracted from the data.weather field.