Hello folks! welcome back to a new edition of our tutorial on AJAX. In this tutorial post, we are going to be discussing about AJAX Action.
This section of our AJAX tutorial gives you a clear understanding of the exact steps of an AJAX operation.
This section of our AJAX tutorial gives you a clear understanding of the exact steps of an AJAX operation.
Steps of an AJAX Operation -
- A client event occurs.
- An XMLHttpRequest object is created.
- The XMLHttpRequest object is configured.
- The XMLHttpRequest object makes an asynchronous request to the server.
- The server returns the result containing the XML document.
- The XMLHttpRequest object calls back the callback() function and then processes the result.
- The HTML DOM is updated.
READ: AJAX | Browser Support
Now we will be discussing about each of the above listed steps one after the other.
A Client Event Occurs
- A JavaScript function is called as the result of an event.
- Example - validateUserId() JavaScript function is mapped as event handler to an onkeyup event on input form field whose Id is set to "userid".
- <input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">
The XMLHttpRequest object is created
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; } } } }
READ: AJAX | Technologies
The XMLHttpRequest object is Configured
In this step, we are going to write a function that will be triggered by the client event and a callback function processRequest() will be registered.
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); }
Making Asynchronous Request to the Server
Source code is available in the above piece of code. Code written in the bold typeface is responsible for making a request to the server. This is done via the XMLHttpRequest object ajaxRequest.
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); }
Aassume you entered Joy in the userid box, then in the above request, the URL is set to "validate?id = Joy".
READ: AJAX | Introduction
Server Returns the Result Containing XML Document
You can implement your server-side script in any language, however its logic should be as follows :
- Get a request from the client.
- Parse the input from the client.
- Do required processing.
- Send the output to the client.
If we assume that you are going to write a servlet, then below is the piece of code -
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>"); } }
Callback processRequest() Function is Called
The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. This function will now receive the result from the server and will do the required processing. Just as in the following example, it sets a variable message on true or false based on the value returned from the server.
function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = ...; ... }
READ: AJAX | Examples
The HTML DOM is Updated
This is the final step and in this step, your HTML DOM will be updated. It happens in the following ways :
- JavaScript gets a reference to any element in a page using DOM API.
- The recommended way to gain a reference to an element is to call.
document.getElementById("userIdMessage"), // where "userIdMessage" is the ID attribute // of an element appearing in the HTML document
- JavaScript may now be used to modify the element's attributes; modify the element's style property; or add, remove, or modify the child elements. Below is an example -
<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>
If you have an understanding of the above mentioned steps, then you are almost done with AJAX.
Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about AJAX XMLHttpRequest.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.