Pure JavaScript Send POST Data Without a Form Pure JavaScript Send POST Data Without a Form javascript javascript

Pure JavaScript Send POST Data Without a Form


You can send it and insert the data to the body:

var xhr = new XMLHttpRequest();xhr.open("POST", yourUrl, true);xhr.setRequestHeader('Content-Type', 'application/json');xhr.send(JSON.stringify({    value: value}));

By the way, for get request:

var xhr = new XMLHttpRequest();// we defined the xhrxhr.onreadystatechange = function () {    if (this.readyState != 4) return;    if (this.status == 200) {        var data = JSON.parse(this.responseText);        // we get the returned data    }    // end of state change: it can be after some time (async)};xhr.open('GET', yourUrl, true);xhr.send();


The Fetch API is intended to make GET requests easy, but it is able to POST as well.

let data = {element: "barium"};fetch("/post/data/here", {  method: "POST",   body: JSON.stringify(data)}).then(res => {  console.log("Request complete! response:", res);});

If you are as lazy as me (or just prefer a shortcut/helper):

window.post = function(url, data) {  return fetch(url, {method: "POST", body: JSON.stringify(data)});}// ...post("post/data/here", {element: "osmium"});


You can use the XMLHttpRequest object as follows:

xhr.open("POST", url, true);xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");xhr.send(someStuff);

That code would post someStuff to url. Just make sure that when you create your XMLHttpRequest object, it will be cross-browser compatible. There are endless examples out there of how to do that.