How to Develop a Web Application with Ajax
See Ajax: Tips and Tricks for similar articles.
Ajax web applications use JavaScript to interact with a server and update web pages without reloading them. The following eight steps show how to develop a simple Ajax web application.
- Create or find your data source URL. An Ajax web application needs a server or other source of data that can be accessed using a URL in order to update the page. For this example, we'll use the following text, saved in a file named
data.txt.Hello, World! This text is loaded using Ajax. - Create the HTML for your application. In the following HTML, I've used a basic HTML5 template containing an
h1element with anidattribute. I've also created a button that will trigger the Ajax functionality on the page when clicked.<html> <head> <title>An Ajax Web Application</title> </head> <body> <h1 id="page-title"></h1> <button id="load-data">Click Here to Load the Data</button> </body> </html> - Create a script block in your HTML (just above the closing
bodytag) and write an event listener to detect click events on the button.<script> document.getElementById("load-data").addEventListener("click",function(){ }); </script> - Use an
XMLHttpRequestobject inside the event listener's callback function to request the data file.var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "data.txt"); - To detect the response, look for a change in the state of the
xmlhttpresponse, using theonreadystatechangeevent handler.xmlhttp.onreadystatechange = function() { //Do something here } - Write a callback function to insert the data from the text file into the
h1element when the state of the response changes.xmlhttp.onreadystatechange = function() { document.getElementById("page-title").innerHTML = this.responseText; } - Use the
send()method to send the request.
The finished HTML page should look like this:xmlhttp.send();<html> <head> <title>An Ajax Web Application</title> </head> <body> <h1 id="page-title"></h1> <button id="load-data">Click Here to Load the Data</button> <script> document.getElementById("load-data").addEventListener("click",function(){ var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "data.txt"); xmlhttp.onreadystatechange = function() { document.getElementById("page-title").innerHTML = this.responseText; }; xmlhttp.send(); }); </script> </body> </html> - Open the HTML page in a browser and click the button. The script will produce the following output in a browser:

