http post request in javascript code example
Example 1: javascript send post request
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
post("post/data/here", {element: "osmium"});
Example 2: javascript send post data with ajax
function makeRequest (method, url, data) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
if(method=="POST" && data){
xhr.send(data);
}else{
xhr.send();
}
});
}
var data={"person":"john","balance":1.23};
makeRequest('POST', "https://www.codegrepper.com/endpoint.php?param1=yoyoma",data).then(function(data){
var results=JSON.parse(data);
});
Example 3: javascript ajax request
function makeRequest (method, url, data) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
if(method=="POST" && data){
xhr.send(data);
}else{
xhr.send();
}
});
}
makeRequest('GET', "https://www.codegrepper.com/endpoint.php?param1=yoyoma").then(function(data){
var results=JSON.parse(data);
});
var data={"person":"john","balance":1.23};
makeRequest('POST', "https://www.codegrepper.com/endpoint.php?param1=yoyoma",data).then(function(data){
var results=JSON.parse(data);
});