Simple Ajax Request – Loading a Text File

        Before starting the tutorial just a look into “what is Ajax ?”. Ajax is nor a programming language neither it is a framework, instead it is a technique used to develop Rich Internet Applications, i.e. applications which are more faster, more graphical and more interactive. AJAX (Asynchronous Javascript and XML) is a combination of several existing technologies rather than being a single technology.

       Here are the basic technologies involved in Ajax applications:
HTML is used to build Web forms and identify fields for use in the rest of your application.
JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.
DHTML, or Dynamic HTML, is used to update your forms dynamically. You'll use div, span, and other dynamic HTML elements to mark up your HTML.
• Server Side Scripting is used to process the query passed by Javascript and returns the response XML.

       Thus with AJAX, a JavaScript can communicate directly with the server(with a XMLHttpRequest object) and transfer data with it asynchronously, i.e. without submitting or reloading the page.

       The XMLHttpRequest object is the key component to Ajax that makes it so useful. It provides a mechanism for the client (through Javascript) to send information to the server and receive a response as XML. The response XML can be processed in the background and used to dynamically update elements on the page. In effect, information flows, and screens are updated, more like in desktop applications than in old-fashioned web applications.

       Now lets move to the coding part. Basic AJAX is normally composed of three JavaScript functions:
1. A function that creates an XMLHttpRequest object
2. A function that calls the XMLHttpRequest object and submits it,
3. A function that handles the information sent back to the page.

       Lets look at the first function. We first declare a variable with name xmlHttp. Now depending upon the browser an ‘xmlHttpRequest’ object is created and assigned to this variable. If the browser is Internet Explorer, then we have to create a new ‘ActiveX Object’ and if the browser is Firefox,Opera etc, then we have to create a new ‘xmlHttpRequest’ which is a built in object. The function then returns the just constructed object.
function getXMLHttp() {
        var xmlhttp;
        if (window.ActiveXObject) {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
        } else {
                alert("Your browser does not support Ajax!");
        }
        return xmlhttp;
}
       In the second function we use the first function to create an xmlHttpRequest object and open an HTTP connection using it. We pass three parameters in the xmlHttp.Open() function. First is the submit method (it can be POST or GET). Second is the URL ,which contains the serve side processing (here to make it simple we are using a text file) and which returns the result to the script as xml. Third is a boolean value which states whether the transfer is asynchronus(true) or synchronus(false). Next we call a function when the ready state changes(loaded, loading, not loaded). Next we send a null to the other page (may not be null for POST , but always null for GET).
function getTextInfo() {
   xmlhttp1=getXMLHttp();
   var url =”"demo1.txt” ;
   xmlhttp1.open("GET",url,true); 
   xmlhttp1.onreadystatechange = updateInfo;
   xmlhttp1.send(null); 
}
       In the ‘readyStateChange’unction we first check whether the reponse is loaded (whether state is 4). The content of the text file is transferred as reponse text. We get the content into a variable and display it to a textarea/div.
function updateInfo() {
        if (xmlhttp1.readyState == 4) {
              var response = xmlhttp1.responseText;
              document.getElementById("showText").value = response;
        }
}
This sums up the tutorial. Hope this was useful for you.
Please enter your valuable comments and suggestions.
You can find the entire code along with html from below.

<html>
<html>
<title>ScriptSplash.com - Simple Ajax Request</title>
<head>
<script language="javascript">
/** Create a cross-browser XMLHttp Request object. **/
function getXMLHttp() {
    var xmlhttp;
    if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
       xmlhttp = new XMLHttpRequest();
    } else {
        alert("Your browser does not support XMLHTTP!");
    }
    return xmlhttp;
}
/** Get the content of a text file using Ajax. **/
function getTextInfo() {
    xmlhttp1=getXMLHttp();
    xmlhttp1.open("GET","AjaxTest.txt",true); 
    xmlhttp1.onreadystatechange = updateInfo;
    xmlhttp1.send(null); 
    return false;
}
/** Check for response and update the text-area. **/
function updateInfo() { 
    if(xmlhttp1.readyState == 4) { 
        response=xmlhttp1.responseText;
        document.getElementById("showText").value = response; 
    } 
}
</script>
</head>
<body>
  <h2>Get content of text file</h2>
  <h4>Click to get the content of a text file via AJAX</h4>
  <form>
  <textarea name="showText" id="showText" style="width:400px;height:400px;"></textarea><br/>
  <input type="button" value="Get Content" onClick="getTextInfo();">
  <form>
</body>
</html>

3 comments:

  1. Simple and informative post. Nice language.

    ReplyDelete
  2. Working great! except it's throwing an error in IE:
    Been trying for several hours to solve it ;-(

    xmlhttp1.open("GET","myfile.txt",true); >> object is null or not defined

    ReplyDelete
    Replies
    1. got a positive vibe from this page ;-)

      needs the full url in IE to properly work as:
      xmlhttp1.open("GET","http://mywebsite.com/myfile.txt",true);

      Can't believe it took me hours to find that one ;-)

      Delete

Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates