What is AJAX?

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

AJAX is a collection of web development techniques that creates asynchronous web applications (i.e. it allows the program to be executed immediately whereas the synchronous code will block further execution of the remaining code until it finishes the current one) on the client-side with the help of various web technologies (like HTML, Javascript, etc.). It is not a language or a framework but a set of rules. It lets web applications send and retrieve data from a server asynchronously without interfering with the display and behavior of the current page.

The AJAX full form is Asynchronous Javascript and XML.

What is AJAX?

Imagine you've decided to learn about AJAX, thus you decide to google What is AJAX? Now you can observe while Googling that the website presents you with different suggestions based on the sentence you've entered so far.

What Is AJAX google search

Earlier (like prior to 2005), in order to change a part of the page, the whole page needed to be refreshed. Thus all the CSS and other redundant UI data used to be loaded again, but now, as we can observe, the website doesn't reload every time the suggestions change, but the suggestion box automatically changes the suggestion according to our search text. This management of the dynamic content of a webpage is achieved using AJAX. Now, the question arises, What is AJAX?

Ajax sets up the communication with a server/database without the need for a postback or a complete page refresh. AJAX can be defined as * the method of exchanging data with a server and updating parts (e.g. the suggestion box in this case) of a web page – without reloading the entire page.* AJAX is the best solution whenever there is a need to update the webpages asynchronously by trading the data with the server. It updates the parts of the web application dynamically and asynchronously without reloading the complete webpage for the application. AJAX is the combination of XMLHttpRequest Object, JavaScript and HTML DOM.

AJAX is not a programming language.

How Does Ajax Work & How is It Different from Conventional Models?

As we have already discussed, AJAX is not a single technology, nor is it a programming language. AJAX is a set of web development techniques that generally comprises the following:

  • It uses HTML or XHTML as the main language and CSS for the presentation. These together make up the UI part.
  • The Document Object Model (DOM) is used to dynamically display data and to set up its interaction with the programming language.
  • XML is used to set up the interchange of the data, and XSLT is used for data manipulation. However, modern-day developers have started to use JSON for the same purposes.
  • The XMLHttpRequest object is used for asynchronous communication.
  • JavaScript is used to gather all these technologies together.

The following diagram depicts the working of AJAX:

working of AJAX

How is it different from conventional models?

The AJAX primarily uses the XHTML for content, CSS for presentation, Document Object Model, and JavaScript for dynamic content display. AJAX is asynchronous, whereas the conventional model transmits the data to the server using synchronous requests.

The following diagram compares the working of the conventional model and the AJAX model:

comparing the working of conventional and AJAX models

Where is Ajax Used?

Ajax can be used in web applications where there is a need to receive small amounts of information from the server without reloading the entire web page. For example, AJAX can be used for data validation in save actions. Also, as discussed above, AJAX can be used to change the values in a drop-down list box based on different inputs.

For e.g. The AJAX eliminates the necessity to submit the form every time we need to validate the sections. AJAX aids us with real-time form validation, thus when the user enters the email in the email address field, it automatically checks if the entered address is in the correct format without entirely reloading the form. The reloading of the entire page is avoided, as AJAX partially updates the webpage.

Benefits of AJAX

Following are some major benefits of using Ajax in web applications:

  • Performing Callbacks: The AJAX can perform a callback to handle responses from the server in Ajax. They make a quick round trip to and from the server to retrieve and/or save data without posting the entire page back to the server. The network utilization is minimized, and operations occur quickly since it is not performing a full postback. This can make a significant improvement in the performance of the websites and locations with restricted bandwidth. The data that is sent to and from the server is usually minimal thus, with the help of callbacks, the server avoids the need to process all form elements. It keeps checking on the amount of processing on the server by sending only the necessary data, thus eliminating the need to process all form elements, process the ViewState, send images back to the client, or send a full-page back to the client.
  • Making Asynchronous Calls: Ajax aids us in making asynchronous calls to a web server. This helps the client browser in avoiding the wait for complete data arrival before allowing the user to process.
  • User-Friendly: Since we are eliminating the page postback thus, applications that have enabled AJAX are relatively more responsive and more user-friendly.
  • Increased Speed: One of the most prominent uses of AJAX is to improve the speed, performance, and usability of a web application. It is because the AJAX loads a smaller amount of data is requested from the server when it is needed rather than loading an entire page, thus reducing the amount of time needed to reload other parts of the page that is not being dealt with. For example, we can observe the rating system on the IMDB website. The users can rate a movie with their personal ratings. Once rated, the rating of that movie gets saved to their database without waiting for the page to refresh or reload.

What are AJAX Actions & the Elements of AJAX?

Whenever an event is triggered by a user on the web page (* e.g. a button click*) an HTTPRequest is sent to the server by the XMLHttpRequest object. It is configured with the request parameter over the network. The XMLHttpRequest would make an asynchronous request to the server. Then, on the server-side, an event listener will handle the request which has been received from the client (*for, e.g., the data retrieved from the database *). The requested data in the form of the XML document is used to build the response, which then is sent back to the XMLHttpRequest, which receives the data using a call back function which then gets processed and updates the HTML DOM to display the page with new data requested by the client.

pictorial representation:

ajax application communication model

AJAX Request (GET/POST)

The GET Request

The GET request is primarily used to retrieve the data from the server. Since the request is asynchronous, so the send() returns immediately; thus, we need to check the location of the response in its life cycle before processing it further. The readyState property of XMLHttpRequest is being used to process this request.

Syntax

Parameters:

  • The required URL parameter specifies the URL to which the request is sent.
  • The optional data parameter specifies a set of the query strings (i.e. key/value pairs) that is sent to the web server along with the request.
  • The optional success parameter is basically a callback function that is executed if the request succeeds. It is typically used to retrieve the returned data.

Note: The readyState is basically an integer value that is used to describe the status of the HTTP request.

Following are the values of the readyState:

  • 0: UNSENT – It states that the request is not initiated yet.
  • 1: OPENED – It states that the server connection is established.
  • 2: HEADER_RECEIVED – It states that the server has received requests successfully. We get this after we have called send(). It simply tells the user that send() has been called, and headers and statuses are available.
  • 3: LOADING – It states that the processing of the request is in progress.
  • 4: DONE – It states that the request is processed and the response is ready at the server.

The readstatechange event gets triggered whenever the readyState property is changed.

The HTTP status code is used to return the status property of the XMLHttpRequest response. Some most commonly used status codes are:

  • 200: It states that the server has processed the request successfully
  • 404: It states that the server can not find the page that has been requested.
  • 503: It states that the server is temporarily unavailable. The common cause for this is a server that is down for maintenance, or that is overloaded.

The POST Request

The POST request is primarily used to submit form data to the server. We can use FormData object or query strings (such as req.send(key=value1&key=value2&..&keyN=valueN)) to send form data. Whenever the is being sent query string, it is needed to explicitly set the request header using setRequestHeader() The data body is encoded.

The setRequestHeader() is called just after open() is called and before calling send().

Following are some most commonly used request headers as part of setRequestHeader()

  • txt/html
  • text/plain
  • application/xml
  • application/json.

Syntax

Parameters:

  • The required URL parameter specifies the URL to which the request is sent.
  • The optional data parameter specifies a set of the query strings (i.e. key/value pairs) that is sent to the web server along with the request.
  • The optional success parameter is basically a callback function that is executed if the request succeeds. It is typically used to retrieve the returned data.

With the help of form data, we can easily construct a set of key/value pairs used for representing form fields, and their values are sent using XMLHttpRequest.send().

AJAX Response

The GET is used to send petite amounts of data to the server and the POST method are used to send the data as part of the HTTP request body. The data that is sent using GET gets sent as a query URL parameter, whereas the data sent as POST data is not visible.

Sending Request and Retrieving the Response:

Instantiating an XMLHttpRequest using

Sending the request to the server, we use open()

Callback Function in AJAX

A callback function refers to a function that is passed as a parameter to some other function.

Callback functions are used when we have more than one AJAX task on our website. In such cases, one can create ONE standard function for creating the XMLHttpRequest object, and this function can be called for each AJAX task.

The function call needs to have the URL and what to do on onreadystatechange (which may differ for each call)

There are two types of callback functions:

  • named callback functions
  • anonymous callback functions

Named Callback Function

In this AJAX callback, named functions are used. The XMLHttpRequest object in named callback functions should be created as a global object outside the functions in the way mentioned below:

Output:

Note: Global variables may cause some problems, thus generally, we use another approach to perform callbacks known as an anonymous callback function.

Anonymous Callback Function

In this AJAX callback, anonymous functions are used. The value of an event handler is set equal to the anonymous function in the following way:

Output

AJAX Security

  • Building XML or JSON dynamically should be avoided. In order to make XML and JSON, one should refer to a safe library to keep the attributes and element data safe.
  • One should always store the data that requires encryption on the server side by using TLS/SSL.
  • We should avoid the use of eval() at the client-side. Rather the usage of .txt should be preferred over .html as the .txt avoids most of the XSS problems.
  • We should always encode the data properly before sending it in order to prevent injection style issues,
  • The code quality should be maintained as poorly written JavaScript code may help hackers to breach the security.
  • The critical business logic should take place on the server instead of the browser side.
  • JavaScript code that is not necessarily needed at load time should be moved to the bottom of the page in order to make the loading process faster. This will make sure that only what is needed first is displayed by the browser.

Server-side Security in AJAX (CSRF Tokens)

  • We should prevent writing serialization code on the server side in order to assure security and avoid breaches.
  • A CSRF token is a secure random token that is used to prevent Cross-Site Request Forgery attacks. We should always use CSRF tokens on the server side.
  • A framework should always be used when we are working with JSON or XML.
  • Authentication, authorization, and other data protection should be specified either in web.xml, or it should be done programmatically.

Practical Examples of AJAX

Following are some practical examples of AJAX:

  • Online rating system
  • Chat rooms
  • Live comment section
  • Search bar suggestions

Advancements That Have Been Made to AJAX

  • Introduction of JSON: As discussed earlier, in AJAX, JavaScript is the client-side programming language, and XML is a markup language to define data. JSON is another markup language to define data. JSON (JavaScript Object Notation) is much easier to use with JavaScript than XML. When it comes to Ajax and JavaScript, JSON Web Services are replacing XML Web Services.

  • Addition of jQuery: Another major advance to JavaScript and Ajax is the JavaScript object library called jQuery. This free, open-source software is a wrapper around JavaScript. jQuery is used to easily write client-side JavaScript to navigate and manipulate a page and make asynchronous Ajax callbacks.

By using jQuery and JSON Web Services, Ajax callbacks have become standard programming practices for designing and developing web applications.

Comparison Table of Conventional Model & AJAX Model

The following table describes how AJAX is different from conventional models:

Conventional ModelAJAX model
In the conventional model, an HTTP request is sent from the web browser to the server.In AJAX, the browser creates a JavaScript call that activates the XMLHttpRequest.
The server receives the data and then afterward retrieves it.The HTTP request to the server by the web browser is created in the background.
The requested data is sent to the web browser by the server. Thus making it less potent than the AJAX model.The server receives, retrieves, and then sends the data back to the web browser.
Every time the web browser receives the data, it reloads the webpage so that the data shows up on the web page. Due to this reloading, users have to wait until the whole process is done, thus making this process time-consuming as well as adding extra load on the server.The data received by the web browser directly appears on the page. In this case, no reloading is needed.

Conclusion

  • AJAX is a collection of web development techniques that creates asynchronous web applications on the client side with the help of various web technologies.
  • AJAX lets web applications send and retrieve data from a server asynchronously without interfering with the display and behavior of the current page.
  • AJAX is not a programming language but a set of web development techniques.
  • AJAX is used in web applications where small amounts of information could be saved or retrieved from the server without posting back the entire pages.