XMLHttpRequest Sample Code

Apr 24, 2019

GET

var URL = ...var req = new XMLHttpRequest();req.onreadystatechange = function() {    if (this.readyState == XMLHttpRequest.DONE) {        if (this.status == 200)          console.log('success', this.responseText);        else          console.log('error', this.status);    }}req.open('GET', URL, true);// req.setRequestHeader('Authorization', 'Bearer ' + token);req.send();

POST Json

var makePost = function(url, data) {  var req = new XMLHttpRequest();  req.onreadystatechange = function() {    if (this.readyState == XMLHttpRequest.DONE) {        if (this.status == 200)          console.log(`done: ${this.responseText}`);        else          console.log(`error: ${this.status}`);    }  }  req.open('POST', url, true);  req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");  // req.setRequestHeader('Authorization', 'Bearer ' + token);  result = req.send(JSON.stringify(data));}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.