Javascript HTTP Request Example Tutorial - XMLHttpRequest

In this blog post, we will see how to trigger a HTTP request through Javascript with a simple example. There are many different ways to invoke a HTTP request, and we will cover all the different types of approaches that exist in the web world to call a web request. The Javascript example presented in this post, are targetted towards beginners. One of the popular method to call an external webpage / internal script is through the XMLHTTPRequest object in Javascript. We will discuss how to do a HTTP GET request with this object.
  <html>
    <script>
      var HTTP_Response_Holder = null ;  
      function loadHTTPData() {
        if (typeof window.ActiveXObject != 'undefined' ) {
          HTTP_Response_Holder = new ActiveXObject("Microsoft.XMLHTTP");
          HTTP_Response_Holder.onreadystatechange = process ;
        }
        else {
          HTTP_Response_Holder = new XMLHttpRequest();
          HTTP_Response_Holder.onload = process ;
        }
        HTTP_Response_Holder.open( "GET", "<your HTTP URL >", true );
        HTTP_Response_Holder.send( null );
      }
  
      function process() {
        if ( HTTP_Response_Holder.readyState != 4 ) return ;
         document.getElementById("output").innerHTML = HTTP_Response_Holder.responsetext ;         
         var links=output.getElementsByTagName("a");     
         var i=0;
         for(i=0;i<links.length;i++)
         {        
                 //do some processing
                
         }       
      }              
    </script>  
    <body>
      <div id="output"></div>
      <button onclick="loadHTTPdata()">LoadData</button>     
    </body>
  </html> 
In this method, we invoke the "loadHTTPdata" function on click of "LoadData" button. This invokes the javascript function, which then uses the XMLHttpRequest object, and invokes a GET request. When this request is successful, it invokes a "process" function. As an example, we have extracted all the hyperlink tags in the document inside this function using the "getElementsByTagName" method.

This approach is straight forward and can be easily plugged into your widget or any javascript code. You can also pass some parameters to this HTTP request and use POST instead of GET if required. That would mean, it is also possible to trigger a PHP or JSP script through this method. To grab the response of the HTTP request, we use the "responsetext" method. In the next post, we will see how to invoke a HTTP request through JQuery. We will also discuss how to achieve the same result using Prototype Javascript framework in subsequent blog posts.

2 comments:

  1. Hi, your example wont work unless the 'T' is capitalized of the method name '.responseText'

    ReplyDelete
  2. Hi, in your sample code, the first 'T' in the field name 'responseText' needs to be capitalized, else it doesn't work

    ReplyDelete