AJax

This is a short introduction to get you start and experience with Ajax. For more information, please refer to "Programming the World Wide Web" by Robert W. Sebesta book and W3 Introduction to Ajax.
(Please let me know if you find any errors or omissions in the document —Upsorn Praphamontripong, 5-June-2022)

Overview

  What is Ajax (Asynchronous Javascript and XML)?  

  • Technique for creating more interactive web apps using XML, HTML, CSS, and JS
  • Unlike the request/response cycle where all communication is synchronous (i.e., the client has to wait for the server to response), Ajax uses JS to allow asynchronous interaction between the client and the server
    • Users do not need to click "submit"
    • Often used to respond to events in the UI

  Two important characteristics  

  • Client requests are handled asynchronously
  • Client modifies only small parts of the current document
Traditional browser-server interaction

Ajax browser-server interaction

  Goal  

  • To improve usability by allowing web apps to respond in ways that look more like desktop apps

  Example application  

  • Help users fill in a form
  • Zip code, city, state ... when a zip code is entered, the client asks the server for the probable city and state
  • JS used to put the response into the form

Ajax Technology

Technologies used in Ajax
  • XML, XHTML, HTML, and JSON for content
  • CSS for presentation
  • DOM to represent and manipulate the structure of XML and HTML documents
  • JS for dynamic content display
    • In the form, JS source files must be referenced in <head> or <body>
    • In the form, an event handler must be registered (for example, using an onblur event or an onkeyup event in the desired form element; or using addEventListener('blur', function-to-be-called))
    • In JS, a response handler must be registered in onreadystatechange property of XMLHttpRequest object
  • XMLHttpRequest (JS object) to perform asynchronous interaction with the server

Browser Support

Here are some of the major browsers that support Ajax. Refer to w3schools for more information.
  • All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object. Syntax for creating an XMLHttpRequest object is
    variable = new XMLHttpRequest(); 
  • Old versions of IE (IE5 and IE6) use an ActiveX Object. Syntax for creating an XMLHttpRequest object is
    variable = new ActiveXObject("Microsoft.XMLHTTP"); 
If none of the above syntax works, it is most likely that a very outdated browser is used.

How does Ajax work

  Ajax web app consists of 4 parts  

  • An HTML document to produce an initial screen
    • An HTML document itself may be produced from .html, .php, .java (servlet), or .jsp
  • A JS to produce an Ajax request
  • A server-side program (i.e., response component) to process the request and produce a response
    • The response component must be on the same server as the original HTML document (for security purpose). Otherwise headers must be set to accept the requests from remote server(s).
    • If the response component must be on a different server, headers must be configured to instruct the server to give the Ajax component the necessary privileges so that the request from the Ajax component can be accepted by the server.
      header('Access-Control-Allow-Origin: http://localhost:4200');
      // header('Access-Control-Allow-Origin: *');
      header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding');
      header('Access-Control-Max-Age: 1000');  
      header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
      Refer to dealing with CORS for more information on header setting for cross-site request.
  • A JS to update the original HTML document based on the response received from the server

  Overview of request / receiver phases  

general view of Ajax

  Request phase  

  • Client communicates to the server with the XMLHttpRequest object
    variable = new XMLHttpRequest(); 

  • The callback must be configured so that the server-side program (i.e., response component) knows which callback function to be invoked. The callback calls the response function. The response function must be registered in onreadystatechange property of the XMLHttpRequest object. Note: Only the code is registered, not the function name.
    xhr.onreadystatechange = receivePlace; 

  • The handler then calls the open() method of the xhr object.
    • Parameters
      • HTTP method (GET or POST)
      • URL of the response component on the server
      • A boolean literal to indicate if the request is asynchronous (true) or synchronous (false)
      • The form data must be attached to the URL if GET is used xhr.open("GET", "zipLookup?zip=" + zip, true)

  • A request is sent with the send method
    xhr.send(); 

  Receiver phase  

  • When the response component on the server finishes, it
    • invokes the specified callback function
    • sends the response object to the client

  • Server returns a sequence of notices, or callbacks, to the client
    Value  readyState  Description
    0 Request not initialized After the XMLHttpRequest object is created but before the open() method has been called, the readyState property of the XMLHttpRequest object is assigned a value of 0.
    1 Server connection established After the open() method has been invoked successfully, the readyState property of the XMLHttpRequest object is assigned a value of 1.
    2 Request received After the send() method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object is assigned a value of 2.
    3 Processing request Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object is assigned a value of 3.
    4 Request finished and response is ready Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object is assigned a value of 4.

  • HTTP response status
    Category Status
    Successful 2xx  200 OK
    Redirection 3xx  301 Moved Permanently
    302 Found
    Client Error 4xx  400 Bad Request
    401 Unauthorized
    403 Forbidden
    404 Not Found
    Server Error 5xx  500 Internal Server Error
    503 Service Unavailable
    504 Gateway Timeout

  • Response component returns data in response to the request from the JS
    • Sebesta's example uses PHP.
      • Response data is produced with a print statement
    • In a servlet, we implement the doGet() method and put the response in the usual Response object.
      • We do not need to send an entire HTML page, just a string of the updated content.
      • We do not need to call setContentType().
      • A security rule requires that the response servlet be on the same server as the original document. However, to work around (and host the response component and the original document on different web servers), we need to configure the header.

  • The callback function updates the HTML document.

  Example (PHP version)  

Front page (popcornA.html)
popcornA.html

Request phase: JS (popcornA.js)
request phase

Response component on the server (getCityState.php) processes the request and returns the result.
request phase (server side)

Receiver phase: (popcornA.js)
receiver phase

  Example (Java Servlet version)  

Front page (popcornForm.java)
popcornForm.java

Request phase: JS (popcorn.js)
request phase

Response component on the server (zipLookup.java) processes the request and returns the result.
zipLookup.java

Receiver phase: (popcorn.js)
receiver phase

Return document options

  • String
  • HTML
  • XML
  • JavaScript Object Notation (JSON)

Security issues

  • If you have security checks in the JS or HTML, security must be repeated on the server (note: users can modify the client-side code).
  • Ajax apps have many small server-side programs, increasing the attack surface of the entire application.
  • Servers that provide JS as a response open themselves up to cross-site scripting attacks.

Copyright © 2022 Upsorn Praphamontripong
Released under the Creative Commons License CC-BY-NC-SA 4.0 license.
Last updated 2022-06-05 14:39