0xCODE
Published in

0xCODE

Javascript AJAX

AJAX — Asynchronous Javascript And XML

AJAX (Asynchronous Javascript And XML) are Javascript techniques that brings more interactive interfaces and faster performance to responsive HTML content on the web. AJAX is an open standard that works in coordination with HTML, CSS and Javascript along side XML. It executes within the Javascript framework with data fetched and stored in XML format. A use case for AJAX is when accessing data from external sources even after a web page has finished loading.

The following is the process behind the AJAX methodology:

  • Data is read from a web server after an HTML page has loaded
  • The data can be updated without requiring reloading the web page
  • Data can be sent to a web server while working in the background

These steps are asynchronous and support an intuitive and natural user interaction with web pages. It is also independent from the web server in that it can execute tasks at any point in time making it a data-driven rather than a page-driven environment.

The XMLHttpRequest Object

The following is an example of how AJAX can change text without requiring the user to reload the web page. This is through the XMLHttpRequest object that sends a request to the web server and then display the result in Javascript DOM (Document Object Model). This is embedded in the HTML page.

<script>
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "data.txt", true);
xhttp.send();
}
</script>

The function called loadData() will fetch the contents of a file called “data.txt” from the web server. It then displays the content through the DOM. The following diagram illustrates the process.

Going back to the code, there is a condition that must be met. The this.readystate == 4 means “complete and response received” and this.status == 200 means the web server response must be HTTP 200 (Status: OK). If the server did not respond, due to a network failure or system downtime, then a status HTTP 200 is not returned. It could either be a 500 (Internal Error), 400 (Bad Request) or 404 (Request Not Found).

The fetch Function

In this next example we use the fetch function which allows sending HTTP request to the web server. This returns a promise in Javascript, or a pending process until it can be fulfilled. The data is not processed immediately but will be handled on the back end by the web server. When there is a result, the web server will then either send back a fulfilled legitimate request or reject the request in the case of a malicious attack. The promise statement uses a .then attribute which describes what action to take when a response is received from the web server.

We are going to use an API to convert the value of currency from a money exchange. Provided you have the API access key, you can get a response from the server. If there is no API access key, the request will be rejected. This exercise will assume that we have an API access key.

document.addEventListener('DOMContentLoaded', function() {   // Send a GET request to the API endpoint
fetch('https://api.exchangeratesapi.io?base=USD')
// PUT response into JSON format
.then(response => response.json())
.then(data => {
console.log(data); });
});

This should return a result similar to the following:

base: "USD"
date: "2021-05-12"
rates: {CAD: 1.21, HKD: 7.77 ....

What happened here was the data format was converted to JSON from the XML format. JSON is an open file interchange format that is supported by many applications, making it a better choice when processing data.

Conclusion

AJAX provides a technique for sending requests without reloading a web page. It has a more dynamic way of providing users an interface to interact quickly with web servers. Without this Javascript framework, it would require a page reload every time in order to send a request. That can be a tedious process and consumes more of a user’s time. AJAX is thus much more efficient with responsive web applications that are the core of today’s e-commerce and online platforms.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Tabora

Vincent Tabora

Editor HD-PRO, DevOps Trusterras (Cybersecurity, Blockchain, Software Development, Engineering, Photography, Technology)