Newby Coder header banner

Javascript Ajax

Ajax allows web pages to request small chunks of data (such as HTML, XML, JSON, or plain text) and use them as required

It was known as Asynchronous JavaScript and XML (Ajax), due to usage of XMLHttpRequest to request XML data

It web API as proxy to request data and update parts of a web page rather than just having browser reload entire page

Any of following Apis is used to make Ajax calls


Working of Ajax

XMLHttpRequest

XMLHttpRequest (which is frequently abbreviated to XHR) was introduced by Microsoft in the late '90s, and has been standardized across browsers

function showIp() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert("Ip address is " + this.responseText);
        }
    };
    xhttp.open("GET", "https://api6.ipify.org/?format=text");
    xhttp.send();
}

Above example prints ip address of system by calling a public rest api which returns ip address of the caller

As in the example, to send an XMLHttpRequest



Fetch

Fetch API is basically a modern replacement for XHR; it was introduced in browsers to make asynchronous HTTP requests easier to do in JavaScript, both for developers and other APIs that are build on top of Fetch

Let's convert the last example to use Fetch instead

Replace XHR code with:

fetch("https://api6.ipify.org/?format=text")
.then(function(response) {
	return response.text();
})
.then(function(text) {
	alert(text);
});

This results in same behaviour of the function to alert user with ip address


Choosing between fetch or XHR

This depends on project specifics

XHR has been around for some time now and has considerable cross-browser support

If not supporting older browsers isn't an issue, then Fetch could be a good choice