Ajax Example : Explanation
Previously we have learnt about the basic and working of the Ajax.
Recommanded Reading : How to execute the Ajax on the local machine ?
Ajax Example :
In this tutorial we will be learning the basic structure of the Ajax using the simple example.
<!DOCTYPE html> <html> <head> <script> function showMsg() { var xmlhttp; // code for IE7+, Firefox, Chrome, Opera, Safari if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("msgDiv").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "msg.txt", true); xmlhttp.send(); } </script> </head> <body> <div id="msgDiv"> <h2>AJAX will change this text</h2> </div> <button onclick="showMsg()">Show Message</button> </body> </html>
Explanation :
In the above program we have two different sections -
<div id="msgDiv"> <h2>AJAX will change this text</h2> </div> <button onclick="showMsg()">Show Message</button>
First is div section and another is button.
Section | Explanation |
---|---|
Div Section | Div section is used to display the response obtained from the server. |
Button | Button will trigger the Ajax call by calling the showMsg() function. |
We need to add a <script> tag to the page’s head section. The script section contains the showMsg() function:
<head> <script> function loadXMLDoc() { // AJAX Script } </script> </head>
In the next chapter we will be learning about the XMLHttpRequest of Ajax.