1let data = {element: "barium"};
2
3fetch("/post/data/here", {
4 method: "POST",
5 body: JSON.stringify(data)
6}).then(res => {
7 console.log("Request complete! response:", res);
8});
9
10
11// If you are as lazy as me (or just prefer a shortcut/helper):
12
13window.post = function(url, data) {
14 return fetch(url, {method: "POST", body: JSON.stringify(data)});
15}
16
17// ...
18
19post("post/data/here", {element: "osmium"});
20
1var xhr = new XMLHttpRequest();
2xhr.open("POST", yourUrl, true);
3xhr.setRequestHeader('Content-Type', 'application/json');
4xhr.send(JSON.stringify({
5 value: value
6}));
1function makeRequest (method, url, data) {
2 return new Promise(function (resolve, reject) {
3 var xhr = new XMLHttpRequest();
4 xhr.open(method, url);
5 xhr.onload = function () {
6 if (this.status >= 200 && this.status < 300) {
7 resolve(xhr.response);
8 } else {
9 reject({
10 status: this.status,
11 statusText: xhr.statusText
12 });
13 }
14 };
15 xhr.onerror = function () {
16 reject({
17 status: this.status,
18 statusText: xhr.statusText
19 });
20 };
21 if(method=="POST" && data){
22 xhr.send(data);
23 }else{
24 xhr.send();
25 }
26 });
27}
28
29//POST example
30var data={"person":"john","balance":1.23};
31makeRequest('POST', "https://www.codegrepper.com/endpoint.php?param1=yoyoma",data).then(function(data){
32 var results=JSON.parse(data);
33});
1const postData = async ( url = '', data = {})=>{
2 console.log(data);
3 const response = await fetch(url, {
4 method: 'POST',
5 credentials: 'same-origin',
6 headers: {
7 'Content-Type': 'application/json',
8 },
9 // Body data type must match "Content-Type" header
10 body: JSON.stringify(data),
11 });
12
13 try {
14 const newData = await response.json();
15 console.log(newData);
16 return newData;
17 }catch(error) {
18 console.log("error", error);
19 }
20 }
21
1<script>
2function loadDoc() {
3 var xhttp = new XMLHttpRequest();
4
5 //looking for a change or state , like a request or get.
6 xhttp.onreadystatechange = function() {
7
8 //if equal to 4 means that its ready.
9 // if equal to 200 indicates that the request has succeeded.
10 if (this.readyState == 4 && this.status == 200) {
11 document.getElementById("demo").innerHTML = this.responseText;
12 }
13 };
14
15 //GET method for gettin the data // the file you are requesting
16 xhttp.open("GET", "TheFileYouWant.html", true);
17
18 //sending the request
19 xhttp.send();
20}
1const Http = new XMLHttpRequest();
2const url='https://jsonplaceholder.typicode.com/posts';
3Http.open("GET", url);
4Http.send();
5
6Http.onreadystatechange = (e) => {
7 console.log(Http.responseText)
8}