POST Method
Learn about the post() AJAX method in jQuery along with an example.
We'll cover the following...
post() method
post() is a jQuery AJAX method that loads data from a server with the help of an HTTP POST request.
The syntax for the post() method is shown below:
jQuery.post(URL, Data, Callback, Datatype)
The description of each parameter is:
-
URL- the specific server address to which the HTTP POST request is made, along with the requested resource/web page. Usually, this will be the URL of the server running your site. -
Data- the information sent to the server via the request message body, usually in the form of key-value pairs. -
Callback- the function executed after the successful completion of the POST request. The callback function receives two arguments,dataandtextStatus.datacontains the response from the server in the specifiedDataType.textStatuscontains the status of the POST request: success, etc. -
DataType- the type of data expected from the server, such as JSON, text, HTML, XML, or others.
📝 Note: In the
post()method,URLis a required parameter, butCallback,DataandDataTypeare optional parameters.
Example: Find the IP address of a website
Consider the example below. A web page takes a website URL from the user as input. Given the URL, the web page displays that URL’s IP address when the button “Find IP” is clicked. The IP address is fetched from a server with the help of a POST request. We do not want the entire web page to reload, so we use the AJAX methods in jQuery. And because we need to send data to the server, we use the AJAX post() method.
Step 1: Getting data from the server
First, request the data from the server using the post() method (lines 4-12). As discussed above, the post() method expects us to specify the URL, Data, DataType, and the Callback function.
- The specific
URLfor the server ishttps://5f28559af5d27e001612eebf.mockapi.io/findIP/(line 4). - The
Datahere is the user-provided website URL, shown in the input box. We provide the data inJSONformat with the text “website” as key and the URL as the value (line 5). For example:
{
"website" : "www.google.com"
}
- The
DataTypeof the expected response isJSON(line 12) with three fieldsid,website, andip. Note that the fieldwebsiteis the one provided in the POST request. - The
Callbackfunction receives two arguments - thedataobject of type JSON and thestatusTextvariable specifying the status of the POST request (line 6). We generate an alert in the callback function (lines 7-10), displaying thedataobject fields and thestatusTextmessage.
📝 Note: This example is for learning purposes only. The server returns a random IP address value for any given website.
Step 2: Adding data to the webpage
The next step is to display the requested data on the webpage. In the callback function, use the text() method to update the text of the div element (line 7). The div text now contains the IP extracted from the data.ip field.