Sending POST Request in JavaScript

To make an HTTP POST request from a web browser, JavaScript offers two primary methods: the promise-driven fetch() API and the callback-driven XMLHttpRequest object. To send POST requests from Node.js, you can use the native "http" module. To make a POST request with JavaScript Fetch API, you must indicate the HTTP POST method name with the "method" parameter and the POST payload in the "body" parameter. Extra HTTP request headers can be set with 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 sending JavaScript POST requests with XMLHttpRequest object. Click "Execute" to make a JavaScript POST request online and see the result.
Sending 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: 31365 times

What is JavaScript?

JavaScript is an interpreted programming language used both on the client and server sides. JavaScript is mainly used to create interactive web applications. JavaScript can manipulate the browser object model, process user input, perform asynchronous operations, and send network requests. JavaScript supports several programming paradigms, such as object-oriented, functional, and event-driven. JavaScript has a large user community and a rich ecosystem of open-source projects that make it easy to collaborate and reuse code written in JavaScript. JavaScript is supported in almost all modern browsers and on all operating systems.

What is Fetch API?

The Fetch API is a modern interface built into most web browsers that provides a powerful and flexible method for making HTTP requests. Unlike XMLHttpRequest (XHR), the Fetch API is promise-based, which makes it easier to send HTTP requests and gives you a more straightforward and cleaner API without nested callbacks. The Fetch API supports GET, POST, DELETE, and other request methods and can retrieve and send data, including text, JSON, and binary data. The Fetch API is the best alternative to XMLHttpRequest and integrates easily with other technologies, such as Service Workers.

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(JSON.stringify(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