DEV Community

Cover image for  the web developer dream - learn the AJAX technique
Gabriele Boccarusso
Gabriele Boccarusso

Posted on

the web developer dream - learn the AJAX technique

The only way to change a web page with new informations is by refreshing the page and working on the requestbut this way is too rude and inefficient. A better way to achieve the same result but with maximum efficiency and professionality is the AJAX protocol.

AJAX stands for Asynchrouns javascript and XML, and, despite the name, can bring any kind of new data in a web page without the need to refresh it by connecting to a database or to an API.

AJAX does essentially two important things:

  • Connect with the server/API
  • Retrieve the data
  • Change the web page

Everyone of this step is at our complete discretion being a technique that offers great flexibility in our ends and a lot of abstraction in how it executes the actual operations.

This technique is used through a javascript object called the XMLHttpRequest:

const ajax = new XMLHttpRequest();
Enter fullscreen mode Exit fullscreen mode

now that we have the object we need to assign a function to the onreadystatechange method that will be called everytime the internal state of the object will change:

ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200 {
        // execute what's here
    }
}
Enter fullscreen mode Exit fullscreen mode

Everything inside the assigned function should always be inside an if statement.
The first thing to check is the readyState attribute of the object.
This attributes can have five different values, ranging from 0 to 4, and 4 means that the operations is fully complete.
For the reference you can go here.

The status attribute refers to the HTTP protocol: 200 means that was successful, 404 that what was requested was not found and so on.
For the complete documentation you can go here.

If readyState and status are on 4 and 200 that means that everything was successful and is in this state that you want to operate any change to the webpage.

Now that everything is set we need only to retrieve the data from the server. with the send function we initialize the request and with the send one we execute the data:

url= 'https://myapi.com';
ajax.open('GET', url, true);
ajax.send();
Enter fullscreen mode Exit fullscreen mode

The open method accept three paramters:

  1. The request method, in most cases we want to get something
  2. The string that represents the URL to send the request to
  3. If the request must be asynchronous, which is obviusly true

the send method is the one that performs all the underline operations needed to perform the changes to the web page.

Integrating AJAX with our backend language of choice is very easy, by using a web server to host our website and PHP we can set the call to a determined script that performs the operations basically creating our own API.

Please note that without a basic knowledge of PHP you'll not be able to fully comprehend the next code.

Let's create a simple webpage that dynamically creates and updates a table.
The only code that we need in our html file is:

    <label for="cols">rows:</label>
    <input type="text" id="cols" name="cols" onkeyup="SetCols(this.value)" onload="this.value=''">
    <label for="rows">cols:</label>
    <input type="text" id="rows" name="rows" onkeyup="SetRows(this.value)">
    <span id="out"></span>
Enter fullscreen mode Exit fullscreen mode

This code define three simple things:

  • an input field for the column of the table
  • an input field for the rows of the table
  • a span that will contain the output of the AJAX request, our table

Before explaining the actual code let's see the variable that we are going to use:

// before calling our backend we have to first polish the data
// that we are going to send.
// php accepts everything as a request
// our variables are just pieces of the request
// that will then be concatenated 
let cols = '';
let rows = '';
let script = '';
let output = document.getElementById("out");

let ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // we receive from the script a table in html
        // and then we replace it with the old one
        output.innerHTML = this.responseText;

    }
}
Enter fullscreen mode Exit fullscreen mode

As we see in the HTML code, everytime we change the value of the input field the dedicated function that sets the rows and the columns get called, let's see them:

function SetCols(ncols) {
    cols = 'cols=' + ncols;
    if (rows != '') {
        CreateTable();
    }    
}

function SetRows(nrows) {
    rows = 'rows=' + nrows;
    if (cols != '') {
        CreateTable();
    } 
}
Enter fullscreen mode Exit fullscreen mode

The functions just sets the rows or the cols variable in a way that PHP understands it and if the other one is not void it calls the createtable function, which:

function CreateTable() {
    script = 'make_ajax_table.php?' + cols + '&' + rows;
    // console.log(script);
    ajax.open('GET', script, true);
    ajax.send();
}
Enter fullscreen mode Exit fullscreen mode

what we are sending to the PHP script is just a line with a request that contains the rows and cols variables.

Now let's see the actual PHP script:

$cols = $_REQUEST['cols'];
$rows = $_REQUEST['rows'];

try {
    $cols = (int)$cols;
    $rows = (int)$rows;
}  
catch (exception $e) {
    echo 'hi, something strange happened. <br> Let the developers know of this error ' . $e;
} 
finally {
    echo '<table border=1>';
    for($i = 1; $i < $cols+1; $i++)
    {
        echo '<tr>';
        for ($j = 1; $j < $rows+1; $j++)
        {
            echo '<td>' . $j * $i . '</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}
Enter fullscreen mode Exit fullscreen mode

Everything that we echo out get transposed as a string and then put into the inner HTML of the span tag.
Let's see the final result:
table that changes height and width based on user input

For the full code you can check the github gist here

Discussion (7)

Collapse
lukeshiru profile image
LUKESHIRU

FYI nowadays we use fetch instead of XMLHttpRequest. So instead of writing something like this:

const ajax = new XMLHttpRequest();
ajax.addEventListener("readystatechange", ({ currentTarget }) => {
    console.log(currentTarget.readyState, currentTarget.status);
    if (this.readyState == 4 && this.status == 200) {
        // execute what's here
    }
});
ajax.open("GET", "https://myapi.com", true);
ajax.send();
Enter fullscreen mode Exit fullscreen mode

You write it like this:

fetch("https://myapi.com").then(response => {
    if (response.ok) {
        // execute what's here
    }
});
Enter fullscreen mode Exit fullscreen mode

Best thing about fetch is that is based on promises.

One other thing, you might want to avoid innerHTML, which is extremely unsafe. If you really want to take html from the backend and set the front end based on that, you might want to use something like DOMParser.

Cheers!

Collapse
z2lai profile image
z2lai

Haha, I think you're being a little too polite there. It's not really nowadays if it's been like this for 10+ years, especially in the world of web dev.

Collapse
suckup_de profile image
Lars Moelleken

Your php example is maybe a little confusing because of the "try catch finally". Casting into "int" from a request will never throw a exception because the request is always a string or an array of strings and that can be converted into integer. (also if the result is maybe unexpected)

3v4l.org/eTdZr

Collapse
mkubdev profile image
Kubdev

Are you Marty Mc Fly ? :')

Collapse
mjcoder_5 profile image
MJCoder

Nice example, no harm in using XMLHttpRequest but now Fetch is being used.

Collapse
heavynounours profile image
Guillaume GAGNAIRE

Welcome to 2009.

Collapse
z2lai profile image
z2lai

Time travellers!