JavaScript

The Principle of Ajax in JavaScript

The name Ajax was first coined in 2005 by Jesse James Garrett in his essay "A New Approach to Web Applications." The idea is to use JavaScript for exchanging data with the server in the background without completely reloading the web page itself.

 

Synchronous Communication

Let's first look at how the classic communication between client and server works via Hypertext Transfer Protocol (HTTP). The client (usually the browser) sends a request (HTTP request) to the server, which then evaluates it and returns a corresponding response (HTTP response) to the client.

 

In terms of web page loading, this means that every time the user clicks on a link or fills out a form, for example, a corresponding HTTP request is sent to the server, which then generates the content of the new web page and returns it to the client.

 

The Principle of Synchronous Communication

 

The less than ideal aspect of this process is that the client or browser has to wait while the server evaluates the request and prepares the response. As a user, you’ll notice this because you’ll no longer be able to interact with the website during this time; that is, no further requests can be made during the waiting time. For this reason, this type of communication, the orderly interplay between starting a request and waiting for the response, is also called synchronous communication.

 

To use a more illustrative example, let's look at the implementation of a classic search function within a web page. A search form is used to enter the criteria for the search, and then the form is submitted. The server evaluates the search request, usually performs one or more database queries, and creates the web page containing the search results (see below). While the server is doing this, the user can do nothing but wait for the results. Only when all search results have been determined and the response has been loaded from the server can the user continue the interaction—for example, browse through the search results in the overview or view each result in detail.

 

Sequence of a Synchronously Implemented Search

 

Asynchronous Communication

When using Ajax, the communication takes place asynchronously, not synchronously, which is why this is referred to as asynchronous communication. Like with synchronous communication, first a complete web page is loaded from the server, or the client makes a request to the server, which processes it and delivers an appropriate response. Unlike synchronous communication, however, asynchronous communication also enables you to send new requests to the server while you are still waiting for the response to requests that have already been sent (see figure below). This makes it possible, for example, to independently update individual parts of a web page with data from the server.

9

The Principle of Asynchronous Communication

 

If we apply this to the search example, then after submitting the search form, the form would be hidden, a progress bar would be displayed, and—after the search was completed—the search results would be displayed (see next figure). The other (fixed) components of the web page, such as the header, navigation, and footer areas, are not reloaded.

 

Workflow of an Asynchronous Search Implementation

 

This has some advantages: First, the data for the fixed components are not retransmitted from the server, which has an overall positive effect on the transmission time. Second, users have the possibility to continue interacting with other components on the website. For example, search results could be retrieved from the server piece by piece instead of all at once. A user could already view part of the search results, call detailed views of the results, and so on, while more search results were gradually retrieved from the server.

 

Note: Overall, asynchronous communication can significantly improve the user-friendliness and usability of a web page (or web application).

 

Technically, of course, HTTP requests are still sent during asynchronous communication as well. The only difference is that these are not triggered directly by the browser but are controlled via JavaScript calls (although synchronous calls are also possible using JavaScript, but more on that later).

 

The difference is illustrated once again in the figure below. Without Ajax (left side in the diagram), the HTTP requests are executed directly by the browser, but when using Ajax (right side in the diagram), this is done by the corresponding JavaScript code. The JavaScript code also handles processing the response from the server—for example, to update the user interface accordingly.

 

Difference between Classic and AJAX-Based Web Applications

 

Typical Use Cases for Ajax

In addition to the example described in the previous section of the search process running in the background, there are a number of other examples of using Ajax, which we’ll briefly present ahead.

Automatic Completion of Input Fields

A classic example is the completion of input fields. The idea is to display input suggestions to the user in the form of a selection list while the user enters text in the corresponding input field (see below), thus preselecting possible selection values. Technically, you register an event listener for the change event of the respective input field, use Ajax to send a request containing the current input to the server, and display the matching values returned by the server in the dropdown list.

9

Automatic Completion of Input Fields

Pagination of Large Records

Another example is the pagination of records (i.e., splitting them into individual pages). Indeed, if there are many different records (e.g., a table of users), it makes sense not to display all records in one long table, but only a part of the data at a time, with the option to switch back and forth between individual parts. As a rule, a navigation option is provided above or below the corresponding table, as shown below.

 

Ajax Is Often Used for Pagination

 

The example can be implemented by first loading only a part of the records from the server via Ajax (the “first page,” so to speak, similar to the search results described earlier). If the user now clicks on the link to another page, the records for this selected page are loaded from the server accordingly.

News Tickers

News tickers, which you may see on news or sports pages, use Ajax to make regular requests to the server and display new messages, if available. To do this, you use the setInterval() method on the client side to send requests to the server at specific intervals via Ajax. If the requests return new messages, these are incorporated into the news ticker accordingly.

Editable UI Components

The concept of Ajax has greatly propelled the proliferation of web applications—that is, web pages that look and feel like classic desktop applications while running in the browser. Tables that allow you to edit individual records are one of the many GUI components used in such applications (see the next figure). Usually, you can start the edit mode by double-clicking on a table cell and then adjust the value in the cell. In the background, the corresponding record is then synchronized with the database on the server via Ajax.

 

Simple Editing of Table Records via Ajax

 

Beyond these use cases, there are plenty of others where Ajax comes in handy. In general, Ajax is useful whenever you want to dynamically load data from or send data to the server without reloading the web page.

 

Data Formats Used

Now the question arises, what data is transferred between client and server, and in what format? In principle, you can use any format, but the following three are used most frequently:

  • HTML: This format is useful if you want to load ready-made GUI components (also called widgets; e.g., calendar components or the like) directly from the server and integrate them into the web page.
  • Extensible Markup Language (XML): This format is suitable if you load structured data from the server (e.g., individual records for a table) and want to generate content on the web page based on this data.
  • JavaScript Object Notation (JSON): Like XML, this format is suitable whenever you want to load data from the server to generate content on the web page based on that data, but it’s much leaner than XML and comparatively easy to process in JavaScript applications.

Editor’s note: This post has been adapted from a section of the book JavaScript: The Comprehensive Guide by Philip Ackermann.

Recommendation

JavaScript: The Comprehensive Guide
JavaScript: The Comprehensive Guide

Begin your JavaScript journey with this comprehensive, hands-on guide. You’ll learn everything there is to know about professional JavaScript programming, from core language concepts to essential client-side tasks. Build dynamic web applications with step-by-step instructions and expand your knowledge by exploring server-side development and mobile development. Work with advanced language features, write clean and efficient code, and much more!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments