06 - AJAX Response Text Example

Let’s create a simple AJAX example now, with what we have seen so far.

First let’s create a folder called Ajax inside the ROOT folder of the Apache Tomcat, and create a new html document that we will use for testing our Ajax development. I have called SimpleAjaxDemo.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>AJAX Demo</title>
        <script>
        function loadAjaxReponseText()
        {
        var xmlHTTPRequest;
        if (window.XMLHttpRequest)
          {// Validation for Internet Explorer 7 and upo, Firefox, Chrome, etc 
          xmlHTTPRequest=new XMLHttpRequest();
          }
        else
          {// Web browser is Internet Explorer 5 or 6 
          xmlHTTPRequest=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlHTTPRequest.open("GET","AjaxTextResponse.txt",false);
        xmlHTTPRequest.send();
        document.getElementById("AjaxResponseTextHere").innerHTML=xmlHTTPRequest.responseText;
        }
        </script>  
    </head>
    <body>
        <form id="form1">
            <h1>AJAX Demo </h1>
            <br/>
            <h2>ResponseText:
            <br/>
            Please click on the button:
            <input type="button" id="submit" value="Click Me!" onclick="loadAjaxReponseText()"/>
            <div id="AjaxResponseTextHere">
            </div>
            </h2>
        </form>
    </body>
</html>

Now, let’s create a new file that will contain the AJAX response, this file should be called: AjaxTextResponse.txt.

Ajax Text Response

Once we have these two files, let’s open a web browser and go to the following URL: http://localhost:8080/Ajax/SimpleAjaxDemo.html

You should see a page like this:

If you click on the Click Me! button, the magic of AJAX is displayed. A new line should be shown displaying the response we define in the AjaxTextResponse.txt file:

Like us on Facebook