AJAX with plain JavaScript

AJAX with plain JavaScript

Introduction

ajax

Ajax stands for “Asynchronous JavaScript + XML” (although JSON is mostly used today), and represents a group of technologies intended for dynamic creation of Web pages. By using AJAX, we improve the quality of interactivity with the user, with the desire to make it as similar as possible to desktop applications (according to the speed of interaction). The idea behind Ajax is that the page on which the Web application takes place is loaded only once, and that all further communication with the server is performed asynchronously without blocking the interface and without reloading the entire page. Asynchronous behavior means that after the user interacts with the interface, the request to the server is accepted by JavaScript and the XMLHttpRequest object, which in the background sends requests to the server and displays the results when they are available, while the user can continue working in the meantime.

Ajax is not without flaws, since Ajax pages are dynamically generated the biggest problem for sites is search engine optimization. Search engines often cannot interpret the site well, which leads to problems in indexing the sites. A similar problem exists with page traffic analysis tools, because a user can spend a whole day on one Ajax page, and classic traffic analysis tools will interpret this as one page view.

XMLHttpRequest object

XMLHttpRequest is the foundation of AJAX and is a JavaScript object used to send HTTP requests. Designed by Microsoft and then accepted by other major browsers and in 2014 became a standard in W3C.

XHR Object Properties

Property Description readyState Numeric value that describes the state of the object, possible states are: 0, 1, 2, 3 and 4

  • state 0: initial value of object after creation
  • state 1: open() method executed successfully; at this stage request headers can be set with the setRequestHeader()
  • function

  • state 2: all response headers have arrived
  • state 3: begins reading the response data part
  • state 4: The response data part was successfully loaded or an error occurred
responseType Text data corresponding to server response type possible values are: “”, “arraybuffer”, “blob”, “document”, “json” and “text” response Property to access the server response body responseText Returns the server response as a string responseXML Returns the server response as XML data status A numeric value corresponding to the HTTP status of the server response. We are most interested in status 200 – an indication that the request was processed successfully statusText Text message corresponding to HTTP server response message (eg “Not Found” or “OK”) timeout Numeric value after which the HTTP request will end; the timeout value should be slightly higher than the time provided for generating the response; the value of the responseText property will be null

in that case
withCredentials Boolean value that defines whether the cross-site Access-Control request requires credentials such as cookies, authorized header or TLS certificate.

XHR Object Methods

Method Description abort() Cancels the current thread getAllResponseHeaders() Returns all header information getResponseHeader() Returns specific header information open(method,url,async,uname,pswd) The function that initiates an HTTP request and the parameters it accepts are:

  • Method: POST, GET, HEADER, PUT, DELETE
  • ULR is the url of the server to which the request is sent
  • Asynchrony can be true or false depending on whether the request is implemented asynchronously or synchronously
  • Username and password are optional arguments that are specified if they are required to access the server
send() Method to send data to the server (if we have anything to send) setRequestHeader(header, value) Adds a label/value pair in the header when sending data. It must be called after open() and before the send() method

Procedure

a) Creating an object

It is created by calling the XMLHttpRequest constructor:

b) Event handler and callback function

Events (events) related to the XHR object

Events related to an XHR object can be:

Type Description Number of occurrences When onreadystatechange This method is the oldest and is supported in all browsers, with it the eventHandler tracks every change in the state of the object (readyState) and “triggers” at every change of state.
loadstart Process started. Once First progress Processing in progress zero or more When loadstart is complete. error With this eventListener we listen for network-level errors:

abortion Process terminated. Once or never load onreadystatechange “triggers” the event every time the state of the object changes, however, we are usually only interested when the state of the object changes to the value: readyState == 4. If information about other states is not important to you and you want to reduce the “triggering” of unnecessary events, maybe a newer and more “modern” approach is better when only one “load” event is generated when the server responds:

loadend The whole process is complete Once It is activated after some error, intentional interruption (abort) or when the load is completed successfully.

c) Defining connection parameters

After creating the XMLHttpRequest object, it is necessary to define basic parameters for communication. This method does not send a request to the web server, but saves its arguments for sending a request later.

Description of method arguments:

  • Method

    Methods that can be used are: POST, GET, HEADER, PUT, DELETE.
    GET method sends request and data through url, with it the request can be cached, the request remains in the history of the browser and can be bookmarked. The downside is the limited size of data that can be passed through the URL, as well as the visibility of the data in the URL (read “insecurity“). Which is why this method is not used for sending important data.

    The POST method does not send data through the URL, but through the send() attribute of the method, so it is safer and is used when confidential data (usually entered by the user) needs to be sent. The POST method is also used when a larger amount of data needs to be sent, given that it does not have a limited data size, as is the case with the GET method. However, with this method, the request cannot be cached, it does not remain in the browser’s history, so it cannot be bookmarked either.
    The HEAD method asks the server for headers from the specified URL without the document content (used, for example, to check the modification date of the resource).

  • URL

    The ULR is the url of the server to which the request is sent

  • Asynchrony of requests

    This parameter defines the asynchrony of the request. It can be true or false. If omitted or defined as TRUE, then the request is asynchronous.

    NOTE:
    The XMLHttpRequest request can also be synchronous, but this is not recommended because if the server does not send a response, the send() method can block the browser. There is no “magic button” that stops the XMLHttpRequest, and no maximum waiting time, so the JavaScript engine does not allow the execution of the request to be stopped once it has been sent.

  • User Name and Password

    Username and password are optional arguments that are specified if they are required to access the server

d) Definition of header data

Syntax

With the method “setRequestHeader()” we can define some values in the request header. It is most often used when sending data to the server with the POST method. The method parameter is in the form of a “key, value” pair.

NOTE:
The “setRequestHeader()” method must be placed between the open() and send() methods.

Application

Most often, data is sent through the parameter of the “setRequestHeader()” method, in which way the data is encoded.

What is encoding?

There are three ways it can be encoded:

Value Description application/x-www-form-urlencoded Default behavior, all characters are encoded before sending (spaces are converted to “+” symbols, and special characters are converted to ASCII HEX values. The data is actually a query string consisting of name/value pairs separated by the “&” sign, where the names are separated from the values by an equals sign “=”, if there are special characters they are converted to ASCII HEX values. multipart/form-data No characters are encoded. This value is required when using forms with a file upload

control
text/plain Spaces are converted to “+” symbols, but there are no other special characters

The “application/x-www-form-urlencoded” content type is used in most cases, except for sending large amounts of binary data or text containing non-ASCII characters as it is inefficient for that. And “multipart/form-data” should be used for form submissions that contain files, non-ASCII data, and binary data.

e) Preparing data for sending

In the case of sending data, it is necessary to prepare the data in a form suitable for sending.

Serializing data into “query string”

a) Simple information

If the data is simple, it is sent as a query string consisting of name/value pairs separated by the “&” sign, where the names are separated from the values by the equal sign “=”, and if there isspecial characters those transferred to ASCII HEX values.

b) Object

If it is an object/JSON, it must first be converted into a string.

After which encode the resulting string:

Decoding and encoding can be checked through online services such as https://www.freeformatter.com/url-encoder.html or http://www.url-encode-decode.com/.

Example

This snippet has similar functionality to the jQuery method serialize()

Serializing data into an array

This snippet has similar functionality to the jQuery method serializeArray()

f) Sending requests

Initiating the connection of a prepared and defined request with the server is done with the send() method. We can use the send(attribute) method attribute to send data to the server. It is precisely with the POST method that this is the main principle of sending data. We simply send all “preparation” data as an attribute of the “send” method. However, since with the GET method we send all the information through the URL, we do not use this possibility of sending through the attribute, but define the attribute with null send(null) or simply do not fill it.

g) Server response

Request status

The status of our request as a server response is accessed using the status

property of the XMLHttpRequest object

to the status text with:

String response

The server response in the form of a “string” is accessed via the responseText

property

NOTE:
XMLHttpRequest does not have a direct property for server response in JSON format, so it is necessary to parse the response:
JSON.parse(xhr.responseText);

XML response

A server response that is some XML is accessed with responseXML

HTTP server response header

Access to all headers returned by the web server is with the help of the method getResponseHeader() :

Examples

EXPLANATION:
In the examples, I use the online resource myjson.com to quickly generate a REST endpoint.

a) Getting data from the server

Example No. 1

I access the JSON file saved on the site http://myjson.com/ via the endpoint: https://api.myjson.com/bins/erxi9. With an ajax request to the endpoint I get the following content:

In this example, all persons who satisfy the selected position are printed:

See the Pen Promise primer by Web programming (@chos) on CodePen.

Example No. 2

For this example I am using the generated endpoint https://api.myjson.com/bins/amz5t.

See the Pen Ajax GET by Web Programming (@chos) on CodePen.

b) Sending data to the server

Example

Example: sending data from a form

c) Sending files to the server