PREREQUISITES

  • For those like me who use Visual Studio Code as an editor, a localJS web server must be installed to run the code examples shown. I used the Live Server extension. Once installed to perform an AJAX request right-click on the HTML page and load the page with the server installed.
  • One example performs an AJAX request of type POST. The data is sent to a PHP script. If you have taken my course on PHP you know that to run a script in Windows you need to have installed the Apache web server listening on port 80. Once you have installed the web server via XAMPP and started it, place the script inside the htdocs folder. More information can be found in my introductory post on PHP. I’ll leave you the link: https://www.marcoalbasini.com/2022/07/introduzione-al-linguaggio-php/

SYNCHRONOUS AND ASYNCHRONOUS CODE

Asynchronous code is nothing more than code that does not go to block the execution of other program instructions. We know that the fundamental element of the Internet is the exchange of data between hosts. An unintelligent strategy would be to make this data exchange happen synchronously, then block the code and wait for the response. A better strategy is to make sure that we allow the program to make the request and then continue its execution; therefore, we do not go and block the execution of the other instructions while waiting for the response. This way of writing code is called asynchronous programming.

INTRODUCTION TO AJAX

With AJAX (Asynchronous Javascript And Xml) we can make network requests asynchronously, retrieving information from external servers without the need to reload the whole page. Although we have xml in the acronym, in reality Ajax can work with text and json files, json having almost entirely replaced xml as the data exchange format. The XMLHttpRequest Is the heart of Ajax. Through this object we can make our http requests for sending and receiving data. Let us now see with a code example how it is possible to read a text file asynchronously.

Copy to Clipboard
Lettura file di testo asincrona

MANAGING AJAX REQUEST STATES WITH ONREADYSTATECHANGE


An AJAX request can take on several states.
To learn about these states we use the property readState. Let’s make a console.log(xhr)
where xhr is the constant that points to the object XMLHttpRequest; we go to the prototype object where we see the various states an AJAX request can take. I reproduce below the image of the states in the prototype.

State

STATES OF AN AJAX REQUEST

  • State 0 is assumed when the instance was created XMLHttpRequest()
  • State 1 when we invoked the open
  • Status 2 when we received the response headers.
  • Status 3 when data is being downloaded
  • Finally state 4 when the operation is completed

To handle the various transitions between states we use the event onreadystatechange event, by doing a switch on the property readyState. Regarding the completion of the operation, before accessing the response we need to check that the operation was successful. We do this with a test on the property status which must take the value 200.

Copy to Clipboard

AJAX AND JSON

We create a JSON file where a set of users are described. Just as we did for a text file, we can retrieve users via an AJAX request
which first reads the JSON file in text format then transforms it into a javascript array thanks to the parse method.
The following code illustrates the steps.

Copy to Clipboard

SEND METHOD POST TYPE REQUESTS

With AJAX we can make POST requests, in which case we will be the one sending data to the server or to a script. In this example we will send a username to a PHP script, test.php which will return a message. Before sending the request we need to add a request header, to do this we use the method setRequestHeader.

xhr.setRequestHeader(“Content-type“,”application/x-www-formurlencoded“);What we want to send to the script test.php we insert it in the method send() in the form of key-value.

xhr.send(‘username=’+username);

I report the HTML code of the request and the PHP script.

Copy to Clipboard
Copy to Clipboard

RETRIEVE DATA FROM EXTERNAL API

JSON placeholder is a REST API that we can use whenever we need sample data. URL https://jsonplaceholder.typicode.com/ We can make requests and have data in JSON format in response. Let’s look at a code example.

Copy to Clipboard
json placeholder

AJAX AND ASYNCHRONOUS CALLBACKS

Let’s create a module httpRequest.js (modules we will see later) to handle AJAX requests. In this way we implement abstraction and code reuse. If we assign the return this.responseText to a variable we have undefined, that is, we fail to retrieve post 1. Assignment is a synchronous operation while we are operating asynchronously, the moment we define the variable we do not have the return value of the function. This is where asynchronous callbacks come into play, what we can do is pass a callback to the function httpRequest, callback executed at the time we have the response being passed as a parameter to the callback itself.

Copy to Clipboard
Copy to Clipboard
Copy to Clipboard

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB