JavaScript - Ajax Requests in Pure Javascript

We can create http requests through pure JavaScript code without any frameworks. We have easiest configuration ways in AJAX and some other frameworks for httprequests. but there is no need to include frameworks like Jquery, Axios at all times for this purpose alone.

XMLHttpRequest - Get


var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {

    if (httpRequest.readyState == 4 && httpRequest.status == 200) {

        var response = {
            data: JSON.parse(httpRequest.responseText)
        };
        console.log(response.data)
    } else if (httpRequest.status != 200) {
        console.log("Asynchrouns request got failed.");
    }
}
httpRequest.open("GET", "<URL>", true);
httpRequest.send();
	

XMLHttpRequest - Post


var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {

    if (httpRequest.readyState == 4 && httpRequest.status == 200) {

        var response = {
            data: JSON.parse(httpRequest.responseText)
        };
        console.log(response.data)
    } else if (httpRequest.status != 200) {
        console.log("Asynchrouns request got failed.");
    }
}
httpRequest.open("POST", "<URL>", true);
httpRequest.send("foo=bar&lorem=ipsum");

XMLHttpRequests - Custom Headers

We can add custom headers also as per ourpur need.


 httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");