GET Method

Learn about the get() AJAX method in jQuery along with an example.

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, data and textStatus. data contains the response from the server in the specified DataType. textStatus contains 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, URL is a required parameter, while Callback, Data, and DataType are 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 URL for the server is https://5f28559af5d27e001612eebf.mockapi.io/weather/ (line 3).
  • The DataType of the expected response is JSON (line 9) with two fields, id and weather.
  • The Callback function receives two arguments: the data object of type JSON and the statusText variable specifying the status of the GET request (line 4). We generate an alert in the callback function (lines 5-7), displaying the data object fields and statusText message.

📝 Note: The example is for learning purposes only. The server returns a dummy weather value of 26 in 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.