In this guide, I explain how to fetch data asynchronously from an external API using AJAX web technology. AJAX and JSON are one of the most important and common combinations in web development.
first of all, what is AJAX?
AJAX stands for Asynchronous JavaScript And XML. But…
AJAX is a misleading name. It might use XML to transport data, but it is equally common to transport data as plain text or JSON text.
AJAX is not a programming language, it allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. Therefore with this technique it is possible to update parts of a web page, without reloading the whole page.
how AJAX and JSON works?
Once the website is rendered on the browser, we have to activate an event (a click for example). This event creates and sends a request to a server (XMLHttpRequest). Once the server receives this request, it process and create the response in JSON format (if you use PHP for this server, read this post). The browser receives the data from the server and updates the page content.
The XMLHttpRequest is a part of standard JavaScript. You don’t need to load a library to use it.
var ajaxRequest = new XMLHttpRequest();
show me the code!
For this example, I’m explaining how to get data from Github API, an external API with AJAX.
First of all, the HTML code that will activate the event, and the table where we populate the result.
<button type="button" onclick="getJSON()">Get the users</button>
<table id="users"></div>

Secondly, the JavaScript function that sends the request:
function getJSON() {
var ajax_req = new XMLHttpRequest();
ajax_req.open('GET', 'https://api.github.com/users', true);
ajax_req.send();
}

After this, we have to complete the JavaScript with the function that receives the request:
function getJSON() {
var ajax_req = new XMLHttpRequest();
ajax_req.open('GET', 'https://api.github.com/users', true);
ajax_req.onload = function() {
//status 200 means everything is ok
if (this.status === 200) {
var json = JSON.parse(this.responseText);
var row = '';
for (i in json) {
row += '<tr><td>' + json[i].login +
'</td><td><img src="' +
json[i].avatar_url + '</td></tr>';
}
document.getElementById('users').innerHTML = row;
}
}
ajax_req.send();
}
And this is what happened when you press the button. The JavaScript takes the JSON and populates the table.
