Sending HTTP POST Request in JavaScript

JavaScript has two methods for sending HTTP POST requests from the browser: fetch(), based on JavaScript promises, and XMLHttpRequest, which uses callbacks. To send HTTP POST and GET requests in Node.js, use the built-in "http" module. In order to send the HTTP POST request using the JavaScript fetch() method, you must specify the HTTP method name in the "method" parameter and the POST data in the "body" parameter. Additional HTTP headers can be specified in the "headers" parameter. In this JavaScript POST request example, we send a POST request to the ReqBin echo URL using the fetch() method. Below are additional examples of JavaScript POST requests with a detailed descriptions. Click "Run" to run the sample JavaScript POST request online and see the result.
Sending HTTP POST Request in JavaScript Execute
fetch('https://reqbin.com/echo/post/json', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ "id": 78912 })
})
.then(response => response.json())
.then(response => console.log(JSON.stringify(response)))
Updated: Viewed: 13420 times

What is JavaScript?

JavaScript is scripting used both on the client-side (in browsers) and the server-side (NodeJs). JavaScript is the primary programming language for the Internet that allows you to make web pages interactive. It can modify HTML and CSS, send requests, and calculate and process data with JavaScript.

What is XMLHttpRequest?

The XMLHttpRequest is a built browser object that is used to communicate with the server in pure JavaScript. You can send data to the server or receive data from the server using the XMLHttpRequest object without reloading the entire web page. The XMLHttpRequest is mainly used in AJAX programming. The jQuery ajax methods are just wrappers for the XMLHttpRequest object. You can use the Fetch API instead of XMLHttpRequest as it is promise-based and results in simpliert and cleaner code. XMLHttpRequest is used mainly for historical reasons, as there is a lot of legacy code based on XMLHttpRequest, as well as the need to support older browsers.

How to POST request using the XMLHttpRequest in JavaScript?

To send an HTTP POST request, we need to first create the object by calling new XMLHttpRequest() and then use the open() and send() methods of XMLHttpRequest. To receive notifications when the status of a request has changed, we need to subscribe to the onreadystatechange event. POST request headers can be added using the setRequestHeader method. Below is an example of submitting JSON to the ReqBin echo URL with XMLHttpRequest object.

JavaScript POST request with XMLHttpRequest object
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://reqbin.com/echo/post/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    console.log(xhr.status);
    console.log(xhr.responseText);
  }};

let data = `{
  "Id": 78912,
  "Customer": "Jason Sweet",
  "Quantity": 1,
  "Price": 18.00
}`;

xhr.send(data);

How to POST request using the Fetch API in JavaScript?

The new Fetch API provides an interface for fetching resources from the server. This new API provides a more powerful and flexible set of features than the XMLHttpRequest object. The Fetch API makes extensive use of "promises" that allow us to more easily handle asynchronous requests. Below is an example of sending JSON to the ReqBin echo URL with Fetch API.

JavaScript POST request with Fetch API
const response = await fetch("https://reqbin.com/echo/post/json", {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
},
body: `{
   "Id": 78912,
   "Customer": "Jason Sweet",
   "Quantity": 1,
   "Price": 18.00
  }`,
});

response.json().then(data => {
  console.log(data);
});

How to POST request using the jQuery Ajax in JavaScript?

If you are using jQuery in your project, it is recommended that you use jQuery Ajax methods instead of the raw XMLHttpRequest object. The jQuery $.post() method allows you to post data to the server in a single line. This is a simple wrapper for the more advanced $.ajax method. Below is an example of sending JSON to the ReqBin echo URL with jQuery Ajax method.

JavaScript POST request with jQuery Ajax
$.ajax({
  type: "POST",
  url: "https://reqbin.com/echo/post/json",
  data: `{
    "Id": 78912,
    "Customer": "Jason Sweet",
  }`,
  success: function (result) {
     console.log(result);
  },
  dataType: "json"
});

How to POST request using the Axios in JavaScript?

Axios is one of the most popular third-party libraries used to make HTTP requests in JavaScript. Axios works with the built-in XMLHttpRequest API, providing a convenient and versatile set of functions for particular tasks such as intercepting HTTP requests and sending simultaneous requests. Axios, like Fetch API, support promises to handle asynchronous requests. To send POST requests with Axios, we use the axios.post() method. Axios also catches HTTP errors in its catch method, eliminating the need for special status code checking before processing the response. Below is an example of sending a request to the ReqBin echo URL with Axios.

JavaScript POST request with Axios
async function postData() {
  let user = {
    Id: 78912,
    Customer: "Jason Sweet",
    Quantity: 1
  };

  try {
    const response = await axios.post("https://reqbin.com/echo/post/json", user);
    console.log("Request successful!");
  } catch (error) {
    if (error.response) {
      console.log(error.reponse.status);
    } else {
      console.log(error.message);
    }
  }
}

await postData();

How do I post Form data using JavaScript?

The Form submit() method posts web form to the destination server specified in the form's action attribute.

HTML Form Example
<form id="contact-form" action="https://reqbin.com/echo/post/form">
  <input type="text" id="fname" name="fname" value="John">
  <input type="text" id="lname" name="lname" value="Smif">
  <input type="submit" value="Submit">
</form>

JavaScript code for posting the form
document.getElementById("contact-form").submit();

How do I post JSON data using JavaScript?

To post data in JSON format using JavaScript/jQuery, you need to stringify your JavaScript object using the JSON.stringify() method and provide a Content-Type: application/json header with your request. Below is an example of sending JSON data using jQuery.

Post JSON data using JavaScript
$.ajax({
  type: "POST",
  url: "https://reqbin.com/echo/post/json",
  data: JSON.stringify({ "userName": userName, "password" : password }),
  contentType: "application/json",
  success: function (result) {
    console.log(result);
  },
  error: function (result, status) {
    console.log(result);
  }
});

How do I post XML data using JavaScript?

To send data in XML format using JavaScript/jQuery, you need to set contentType to application/xml and dataType to text. Below is an example of sending XML data to the ReqBin echo URL.

Post XML data using JavaScript
$.ajax({
  type: "POST",
  url: "https://reqbin.com/echo/post/xml",
  data: "", 
  contentType: "text/xml",
  dataType: "text",
  success: function (result) {
    console.log(result);
  },
  error: function (result, status) {
    console.log(result);
  }
});

How to send an HTTP POST request in Node.js?

Node.js provides several methods for making HTTP requests. The following example sends an HTTP POST request to the ReqBin echo URL using Node.js, the "request" library.

HTTP POST request with Node.js
let request = require('request');

request.post(
    'https://reqbin.com/echo/post/json',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);

See also