JavaScript POST

Harshit Jindal Oct 12, 2023
  1. Use XHR(XML HTTP Request) to Send POST Data Without a Form in JavaScript
  2. Use the Fetch API to Send POST Data Without a Form in JavaScript
  3. Use the Navigator.sendBeacon() to Send POST Data Without a Form in JavaScript
JavaScript POST

This tutorial teaches how to send post data without using a form in JavaScript.

Use XHR(XML HTTP Request) to Send POST Data Without a Form in JavaScript

XHR is an object that is used to make HTTP requests in JavaScript. It helps to interact with the server and to exchange the data between the client and the server. We can pull data from a server even without refreshing the entire page. It enables users to continue working by disrupting only a part of a page. We can use this method to send POST data without using a form.

const URL = 'delftstack.com'
var xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({name: 'DelftStack'}));

Use the Fetch API to Send POST Data Without a Form in JavaScript

JavaScript Fetch API, like XHR, helps to send HTTP requests to the server. But XHR did not make use of promises and lead to cluttered and unclean code. To use the Fetch API, we have to call the fetch() method. It accepts the following parameters:

  • URL: The URL of the API from which to request data.
  • An object: It is an object specifying additional properties about the type of request made. It has 3 properties:
    • method: It specifies the method like GET, POST, etc. Its value should be POST in this case since we are making a POST request.
    • body: body object contains the data to be sent.
    • headers: It is an optional parameter that helps us to perform various actions on HTTP request and response headers.

After the fetch() method, we specify the promise method then() and catch(). If the promise returned by fetch() is resolved, then the function specified in then() is executed otherwise the promise is rejected and the function inside catch() is called.

let data = {name: 'DelftStack'};
fetch('https://randomuser.me/api/?results=10', {
  method: 'POST',
  body: JSON.stringify(data)
}).then(res => {
  console.log('Promise resolved', res);
});

Use the Navigator.sendBeacon() to Send POST Data Without a Form in JavaScript

Navigator.sendBeacon() method helps send data to a web server over HTTP requests asynchronously. Its main application is to send website analytics data to the server, but it can also be used to send POST data.

let data = {name: 'DelftStack'};
navigator.sendBeacon('https://randomuser.me/api/?results=10', data);
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn