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.

  1. 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.
  2. Create the HTML for your application. In the following HTML, I've used a basic HTML5 template containing an h1 element with an id attribute. 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>
  3. Create a script block in your HTML (just above the closing body tag) and write an event listener to detect click events on the button.
    <script>
    document.getElementById("load-data").addEventListener("click",function(){
    
    });
    </script>
  4. Use an XMLHttpRequest object inside the event listener's callback function to request the data file.
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "data.txt");
  5. To detect the response, look for a change in the state of the xmlhttp response, using the onreadystatechange event handler.
    xmlhttp.onreadystatechange = function() {
    	//Do something here
    }
  6. Write a callback function to insert the data from the text file into the h1 element when the state of the response changes.
    xmlhttp.onreadystatechange = function() {
    	document.getElementById("page-title").innerHTML = this.responseText;
    }
  7. Use the send() method to send the request.
    xmlhttp.send();
    
    The finished HTML page should look like this:
    <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>
  8. Open the HTML page in a browser and click the button. The script will produce the following output in a browser:Result of Running Script and Clicking Button in Browser