Ajax

AJAX - Action

AJAX - Action

In the AJAX workflow, the XMLHttpRequest object plays a key role. Here are the steps of AJAX action -

  • The user prompts an event on the web page by clicking a button. This creates a JavaScript function. For example, the JavaScript function - validateUserId()  is mapped as an event handler after the client triggers an event. 
  • The JavaScript calls to create an XMLHttpRequest object. The syntax for creating the XMLHttpRequest object looks like this -
var ajaxRequest;  // The variable that makes Ajax possible!
function ajaxFunction() {
   try {
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
   } catch (e) {
   
      // Internet Explorer Browsers
      try {
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      
         try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
      
            // Something went wrong
            alert("Your browser broke!");
            return false;
         }
      }
   }
}

 

The function processRequest() for XMLHttpRequest Object is configured which then sends HTTP request to server. The syntax looks like this -

function validateUserId() {

 ajaxFunction();
   
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatechange = processRequest;
   
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
}

 

  • Using PHP, ASP.Net, etc., the server interacts with the database and then returns the asynchronous request. For example, let us assume that you enter - Rainbow in the user id box, then the URL will be set to "validate?id = Rainbow"
  • The returned request contains the XML document. However, the user can execute the server-side script in the language of his choice. Here is the servlet for processing the request -

public void doGet(HttpServletRequest request,

   HttpServletResponse response) throws IOException, ServletException {

   String targetId = request.getParameter("id");

   if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("<valid>true</valid>");
   } else {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("<valid>false</valid>");
   }
}

The processRequest() function is called to get the results from the server and undergo processing. Depending on the returned value from the web server, it will set the variable message to either true or false -

function processRequest() {
   if (req.readyState == 4) {
      if (req.status == 200) {
         var message = ...;
...
}

HTML DOM gets updated and results are displayed in the form of CSS data. The DOM API notifies JavaScript to refer to a certain element or elements in the page. 

document.getElementById("userIdMessage"), 
// where "userIdMessage" is the ID attribute 
// of an element appearing in the HTML document

JavaScript can modify attributes of the element or change its style, properties, etc. The results are then displayed in CSS. The syntax will look like this -

<script type = "text/javascript">
   <!--
   function setMessageUsingDOM(message) {
      var userMessageElement = document.getElementById("userIdMessage");
      var messageText;
      
      if (message == "false") {
         userMessageElement.style.color = "red";
         messageText = "Invalid User Id";
      } else {
         userMessageElement.style.color = "green";
         messageText = "Valid User Id";
      }
      
      var messageBody = document.createTextNode(messageText);
      
      // if the messageBody element has been created simple 
      // replace it otherwise append the new element
      if (userMessageElement.childNodes[0]) {
         userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
      } else {
         userMessageElement.appendChild(messageBody);
      }
   }
   -->
</script>

<body>
   <div id = "userIdMessage"><div>
</body>