Computer lessons

WEB design AJAX technology - learning Ajax using an example. JavaScript - Asynchronous AJAX requests with examples Example of AJAX work

A lesson in which we will look at creating simple asynchronous AJAX requests to the server using examples. We will use both the GET and POST methods as the request transmission method. On the server, we will process requests using PHP scripts.

What is an asynchronous AJAX request?

AJAX technology is mainly used to create asynchronous requests to the server. An asynchronous request is one that runs in the background and does not interfere with the user's interaction with the page.

When sending an asynchronous request, the browser (page) does not “freeze”, i.e. you can work with it as before. But then how do you know when the response from the server arrives? To determine this, you need to monitor the browser's readyState property. This property contains a number whose value can be used to determine what stage the request is in. The following table shows the main values ​​of the readyState property and their corresponding states.

Those. It turns out that we need to track when the value of the readyState property is equal to 4. This will mean that the sent request received a response from the server. The remaining values ​​are used quite rarely in practice, and some browsers may not support them.

In order to determine what stage the request is at, you must use the XMLHttpRequest object's onreadystatechange event. This event occurs every time the value of the readyState property changes. Therefore, in the handler of this event (unnamed or named function), you can write actions that will check whether this property is equal to 4 and if it is equal, then, for example, display the server response on the page.

Creating an asynchronous AJAX request (GET method)

Let's look at creating an asynchronous AJAX request using an example, which will greet the user after loading the page and display his IP address.

To do this, you need to create 2 files on the server in one directory:

  • welcome.html – HTML page that will be displayed to the user. On the same page we will place a script that will carry out all the necessary actions for AJAX to work on the client side.
  • processing.php – PHP file that will process the request on the server side and generate a response. Let's start development by creating the basic structure of the welcome.html file
  • An example of AJAX work An example of AJAX work // Here we will place the JavaScript code that will send a request to the server, receive it and update the contents of the page. All this will work without reloading the page

    Let's look at the sequence of actions that need to be performed on the client side (in JavaScript code):

    Let's prepare the data necessary to execute the request on the server. If no data is needed to complete the request on the server, then this step can be skipped.

    Let's create a variable that will contain an instance of the XHR object (XMLHttpRequest).

    Let's configure the request using the open() method.

    The following parameters are specified:

    • The method by which the request will be sent to the server (GET, POST).
    • The URL that will process the request on the server.
    • Request type: synchronous (false) or asynchronous (true).
    • Username and password if required.
  • Let's subscribe to the onreadystatechange event of the XHR object and specify the handler as an anonymous or named function. After that, we will create code inside this function that will check the response status and perform certain actions on the page. The response that comes from the server is always in the responseText property.

    In addition to checking the value of the readyState property number 4, you can also check the value of the status property. This property determines the status of the request. If it is equal to 200, then everything is OK. Otherwise, an error occurred (for example, 404 - URL not found).

    Let's send a request to the server using the send() method.

    If we use the GET method to send a request, then there is no need to pass data to the parameter of this method. They are sent as part of the URL.

    If we use the POST method to send a request, then the data must be passed as a parameter to the send() method. In addition, before calling this method, you must set the Content-Type header so that the server knows in what encoding the request came to it and can decrypt it.

    Contents of the script element:

    // 2. Creating the request variable var request = new XMLHttpRequest(); // 3. Setting up the request request.open("GET","processing.php",true); // 4. Subscribe to the onreadystatechange event and process it using the anonymous function request.addEventListener("readystatechange", function() ( // if the request states are 4 and the request status is 200 (OK) if ((request.readyState==4) && (request.status==200)) ( // for example, output the XHR object to the browser console console.log(request); // and the response (text) that came from the server in the alert window console.log(request.responseText) ; // get an element with id = welcome var welcome = document.getElementById("welcome"); // replace the contents of the element with the response that came from the server welcome.innerHTML = request.responseText; ) )); // 5. Sending a request to the server request.send();

    As a result, the welcome.html file will have the following code:

    Example of AJAX working Example of AJAX working window.addEventListener("load",function() ( var request = new XMLHttpRequest(); request.open("GET","processing.php",true); request.addEventListener("readystatechange" , function() ( if ((request.readyState==4) && (request.status==200)) ( var welcome = document.getElementById("welcome"); welcome.innerHTML = request.responseText; ) )); request.send(); ));

    On the server (using php):

  • Let's get the data. If the data is sent via the GET method, then from the global array $_GET["name"] . And if the data is transferred using the POST method, then from the global array $_POST["name"] .
  • Using this data, we will perform some actions on the server. As a result, we get some answer. Let's display it using echo .