Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 17, 2021 08:33 am GMT

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();

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    }}

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();

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>

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;    }}

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();    } }

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();}

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>';}

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


Original Link: https://dev.to/gabrieleboccarusso/the-web-developer-dream-learn-the-ajax-technique-9fg

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To