AJAX in JavaScript. Code examples open

AJAX in JavaScript. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

The JavaScript code can interact with any resource on the Internet. A technology such as AJAX is usually used to interact with the server JavaScript code. AJAX is a technology for sending requests to the server from client-side JavaScript code without reloading the page.

There are various ways to create applications that use AJAX. But the most common way is to use the XMLHttpRequest object:

    const xhr = new XMLHttpRequest();

After creating the XMLHttpRequest object, you can send requests to the server. But first you need to call the open() method to initialization:

    XMLHttpRequest.open(method, url[, async[, user[, password]]])

This function takes five parameters, of which the first two are required:

  • method: request type (“GET”, “POST”, “PUT”, “DELETE”, etc.)
  • url: address of the resource to which the request is sent
  • async: A boolean value that indicates whether the request will be asynchronous. If true (the default), then the request is asynchronous
  • user: username used when authenticating to the server (i.e. to determine which user made the request), defaults to null
  • password: the user’s password, which is used when authenticating to the server, is null by default
Synchronous and asynchronous mode differ in that the request is in synchronous mode until the request is executed, the rest of the code JavaScript cannot be executed.

For example, a GET request to “http://localhost/hello“:

    request.open("GET", "http://localhost/hello");

After the request has been initialized, the request can be sent using the send() method:

    XMLHttpRequest.send(body)

The data that is sent to the server is passed as a parameter to the send() method.

XMLHttpRequest request statuses

The XMLHttpRequest object has a number of properties that allow you to control the execution of the request:

  • status – contains the status code of the HTTP response that came from the server. With the help of the status code, you can judge the success of the request or the errors that might occur during its execution.

    For example, a status code of 200 indicates that the request was successful. The 403 code indicates that authorization is required to complete the request, and the 404 code indicates that the resource was not found, and so on.

  • statusText – returns the response status text, e.g. “200 OK
  • responseType: returns the response type. There are the following types:
    “”: empty line
    “arraybuffer”: the response represents an object ArrayBuffer, which contains binary data
    “blob”: the response is a Blob object that contains binary data
    “document”: the response represents an HTML/XML document
    “json”: the response represents the data in JSON format
    “text”: response represents text
  • response – returns the server response
  • responseText – returns the server response as text
  • responseXML – returns XML/HTML, if the response from the server is in the format XML/HTML
  • readyState – stores the state of the request, which represents a number:
    0: the XMLHttpRequest object has been created, but the open() method has not yet been called to initialize the object
    1: the open() method has been called, but the request has not yet been sent by the send() method
    2: the request has been sent, the headers and status of the response have been received and are ready to be used
    3: response received from the server
    4: request completed (even if an error code is received, such as 404)
  • load – fires after the request has been executed. The onload property is used to set the handler
  • readystatechange: occurs every time the value of the readyState property changes. The onreadystatechange property is used to set the handler

Make an AJAX request

Sample code for making a request:

    const xhr = new XMLHttpRequest();
    // GET-resource request /hello
    xhr.open("GET", "/hello");

    // server response handler
    xhr.onload = () => {
        if (xhr.status == 200) { // if response code is 200
            console.log(xhr.responseText); // output the received response to the browser console
        } else {    // otherwise display the status text
            console.log("Server response: ", xhr.statusText);
        }
    };

    xhr.send();  // execute the request

If the request was successfully processed, then by default the server sends a status code of 200.

If in the process of accessing the server some error occurred or the status code is not 200, then using the property xhr.statusText displays the response status text.

In the example above, a relative path was used, but an absolute path could also be used, specifying the protocol, server and port addresses:

    xhr.open("GET", "http://localhost:3000/hello");

Instead of the load event, we could also handle the readystatechange event of the XMLHttpRequest object, which is raised every time the value of the readyState property changes:

    const xhr = new XMLHttpRequest();
    xhr.open("GET", "/hello");
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {                  // if the request is completed
            if (xhr.status == 200) {                // if response code is 200
                console.log(xhr.responseText);      // output the received response to the browser console
            } else {                                // otherwise display the status text
                console.log("Server response: ", xhr.statusText);
            }
        }
    };
    xhr.send();

Sending data to Ajax

For send data to JavaScript, the XMLHttpRequest object is passed the data to be sent to its send() method.

    //data for send
    const text = "Text";

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/post-page");

    // server response handler
    xhr.onload = () => {
        if (xhr.status == 200) {
            console.log(xhr.responseText);
        } else {
            console.log("Server response: ", xhr.statusText);
        }
    };

    xhr.send(text); 

Sending JSON

In a similar way, you can send data that is more complex in structure. For example, consider sending JSON.

JSON in Javascript. Code examples open
JSON in Javascript. Code examples
September 8, 2022
Roman-tk
    const user = {
        name: "Alexander",
        age: 33
    };
    // encode object in json format
    const data = JSON.stringify(user);
    const xhr = new XMLHttpRequest();

    xhr.open("POST", "/user");
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onload = () => {
        if (xhr.status == 200) {
            const user = JSON.parse(xhr.responseText)
            console.log(user.name, "-", user.age);
        } else {
            console.log("Server response: ", xhr.statusText);
        }
    };

    xhr.send(data);

When sending data using the setRequestHeader() method, set the “Content-Type” header to “application/json“, thus indicating that we are sending data in JSON format.

In the load event handler, we first parse the response text from JSON format into a standard JavaScript object:

    const user = JSON.parse(xhr.responseText)

Promise in Ajax requests

To create an additional level of abstraction in this case, it is convenient to use the Promise object, which wraps an asynchronous operation into a single object, which allows you to define actions to be performed on success or failure performing this operation.

We encapsulate the asynchronous request in a Promise object:

    function get(url) {
        return new Promise((succeed, fail) => {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", url);
            xhr.addEventListener("load", () => {
                if (xhr.status >= 200 && xhr.status < 400)
                    succeed(xhr.response);
                else
                    fail(new Error(`Request failed: ${xhr.statusText}`));
            });
            xhr.addEventListener("error", () => fail(new Error("Network error")));
            xhr.send();
        });
    }

The get method takes the address of the server resource as a parameter and returns a Promise object.

The Promise constructor takes a callback function as a parameter, which in turn takes two parameter – two functions: one is executed on successful processing of the request, and the second – on unsuccessful.

Let’s create a test request:

    get("http://localhost:3000/hello")
        .then(response => console.log(response))
        .catch(error => console.error(error));

For error handling, we can use the catch() method, which is passed an error handling function.

    function post(url, data) {
        return new Promise((succeed, fail) => {
            const xhr = new XMLHttpRequest();
            xhr.open("POST", url);
            xhr.addEventListener("load", () => {
                if (xhr.status >= 200 && xhr.status < 400)
                    succeed(xhr.response);
                else
                    fail(new Error(`Request failed: ${xhr.statusText}`));
            });
            xhr.addEventListener("error", () => fail(new Error("Network error")));
            xhr.send(data);
        });
    }
    post("http://localhost:3000/user", "Tom")
        .then(response => console.log(response))
        .catch(error => console.error(error));
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation