Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.
If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the EventSource interface. For full-duplex communication, WebSockets may be a better choice.
Constructor
XMLHttpRequest()
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
Event handlers
‘onreadystatechange’ as a property of the XMLHttpRequest instance is supported in all browsers.
Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.
More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard ‘addEventListener()’ APIs in addition to setting on* properties to a handler function.
Starting Code
const getBtn = document.getElementById('get-btn');
const postBtn = document.getElementById('post-btn');
const getData = () => {};
const sendData = () => {};
getBtn.addEventListener('click', getData);
postBtn.addEventListener('click', sendData);
Method 1 : OnLoad()
//Step 1
const getBtn = document.getElementById('get-btn');
const sendHttpRequest = (method, url) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
xhr.onload = () => {
const data = xhr.response;
console.log(data)
}
xhr.send();
}
const getData = () => {
sendHttpRequest('GET', 'https://reqres.in/api/users')
}
getBtn.addEventListener('click', getData);
Method 2 : Using Promise it will work
const getBtn = document.getElementById('get-btn');
const sendHttpRequest = (method, url) => {
const pomiseObj = new Promise((resolve, reject)=> {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
xhr.onload = () => {
resolve(xhr.response);
}
xhr.send();
})
return pomiseObj;
}
const getData = () => {
sendHttpRequest('GET', 'https://reqres.in/api/users').then((responseData)=>{
console.log('promiseObj Response Data : ',responseData)
})
}
getBtn.addEventListener('click', getData);
Method 3 : Outgoing Request with Invalid POST request , Here Stringify POST data in xhr.Send()
const getBtn = document.getElementById('get-btn');
const sendHttpRequest = (method, url, data) => {
const pomiseObj = new Promise((resolve, reject)=> {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
//To make the post request valid we have to add the setRequestHeader to xhr before we send
if(data){
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.onload = () => {
resolve(xhr.response);
}
xhr.send( JSON.stringify(data) ); // Stringify data to POST request
})
return pomiseObj;
}
const sendData = () => {
sendHttpRequest('POST', 'https://reqres.in/api/register', {
email: 'eve.holt@reqres.in',
password: 'pistol'
}).then((responseData)=>{
console.log('promiseObj Response Data : ',responseData)
})
}
getBtn.addEventListener('click', getData);
Method 4 : Error Handling , onError block in the xhr we reject the promise , it will be received in the catch block
const postBtn = document.getElementById('post-btn');
const sendHttpRequest = (method, url, data) => {
const pomiseObj = new Promise((resolve, reject)=> {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
//To make the post request valid we have to add the setRequestHeader to xhr before we send
if(data){
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.onload = () => {
if(xhr.status >= 400){
reject('Something Went Wrong.')
} else {
resolve(xhr.response);
}
}
//Error Block , Here if we did not check the status code we will get the error message in success block,
//to avoid that we have to validate the status code in the onload() method.
// onError = () => {
// reject('Something Went Wrong.')
// }
xhr.send( JSON.stringify(data) ); // Stringify data to POST request
})
return pomiseObj;
}
const sendData = () => {
sendHttpRequest('POST', 'https://reqres.in/api/register', {
email: 'eve.holt@reqr.in',
password: 'pisto'
}).then((responseData)=>{
console.log('promiseObj Response Data : ',responseData)
}).catch((errordata)=> {
console.log('errordata : ', errordata)
})
}
postBtn.addEventListener('click', sendData);