Requesting a file using Firefox, XMLHttpRequest object and ASP.net

Here is a short sample of Javascript code using the XMLHttpRequest object to request a file from a ASP.net server.

Please note that the Javascript code relies you on using Firefox and running ASP.net development server on localhost.

  1. Create a new website in Visual Studio.
  2. Create a new folder (call it whatever you want) in the project using the solution explorer in Visual Studio
  3. Navigate to the Default.aspx page.

Once in the Default.aspx insert a HTML input button using:

    
    <input id="btn1" type="button" value="Click me" onclick="btn1Click" />
 

Also create a new div element just below the button:

    <div id="divContent"></div>

Next insert the following Javascript code between the section:

   <script type="text/javascript">
   var xmlhttpReq = new XMLHttpRequest()

The above Javascript code declares a new XMLHttpRequest object which we will use later on.

Next declare another variable called divContentElement:

   var divContentElement;

This variable will hold the div element which you created earlier on the Default.aspx page.

Next create a function called btn1OnClick() on the aspx page, since this piece of java-script code is executed locally, and occurs as soon as a user clicks on the button on the page:

    
    function btn1OnClick()
    {
      try
      {
        xmlhttpReq.onreadystatechange = reportStatus();
        xmlhttpReq.open("GET", "http://localhost:1041/files/data.txt",false);
        xmlhttp.send(null);
        xmlhttp.onreadystatechange = reportStatus();
        printOutput("Data: " + xmlhttp.responseText);
        printOutput(xmlhttp.getAllResponseHeaders());
      }
      catch(Error)
      {
        alert(Error);
      }
      return false;
    }

What the code above does is:

onreadystatechange method = sets or retrieves an event handler for asynchronous requests.

open method = initialises the connection with the server using a required HTTP method parameter GET / POST / HEAD, required URL of the web resource, optional Boolean flag stating whether asynchronous communication is needed or not.

The open method takes a file called data.txt which is found in a folder called ‘files’ located on the ASP.net server. You may need to change the port number (1041) depending on which port the ASP.net server is running on your computer.

send method = sends HTTP request to server - result is the response from the server.

responseText method = retrieves the response from the server in text format, if the file on the server was of XML content then responseXML would have been used.


function reportStatus()
      {
            switch (xmlhttp.readyState)
        {
              case 0:
           printOutput('starting up');
           break;
          case 1:
           printOutput('opened successfully');
           break;
          case 2:
           printOutput('request sent success');
           break;
          case 3:
           printOutput('receiving data');
           break;
          case 4:
           printOutput('transfer done');
           break;
          default:
           alert('asynch');
           break;
         }
      }

The above code is a helper method which scans through the state of the XMLHttpRequest object.

   
   function printOutput(data)
   {
     div = document.getElementById('divContent');
     div.style.fontFamily = "Arial";
     div.innerHTML += "" + data;
   }

The above code is again a helper method which gets a handle on the div element initially created on the web page, the parameter ‘data’ is a string object which is appended inside the div element - using the innerHTML attribute.

If all goes to plan the content of the file will be placed on the ASPX page asynchronously, and also without any need to post back to the server for data which would have occurred if I had used a ASP button.

Last updated on 17 Jan 2009
Published on 17 Jan 2009