Voice of a Developer: XMLHttpRequest API - Part 24


The Web offers a variety of APIs to build your app or website. You could access using JavaScript code. These days the browser offers many APIs to developers. In this article, we will explore the XMLHttpRequest API.
Before moving further let us look at the previous articles of the JavaScript series:

XMLHttpRequest (XHR)

It is basic of client / server communication via Browser. This API provides an easy way to get data from URL without full refresh. It was originally developed by Microsoft, and adopted by others like Google, Apple, and Mozilla. The advantage is to update parts of a web page, without full refresh or reloading the whole page.
XHR is used by many popular frameworks like AngularJS, e.g., $http is a service which operates on this. If you read the AngularJS code.
You will find $http service description:
    * @description
    * The `$http` service is a core Angular service that facilitates communication with the remote
    * HTTP servers via the browser's [XMLHttpRequest]
    * object or via [JSONP]
In 1st example we will create XHR object and download jQuery by sending GET request,
  1. varmyRequest = new XMLHttpRequest(); //myRequest is an object created by XHR API    
  2. console.log(typeof(myRequest)); // object    
  3. myRequest.open('GET''https://code.jquery.com/jquery-2.2.3.min.js');    
  4. myRequest.send();    
  5. myRequest.onreadystatechange = function()    
  6. {    
  7.     if (myRequest.readyState == 4 && myRequest.status == 200)    
  8.     {    
  9.         console.log(myRequest.responseText);    
  10.     }   
Hence, we will get jQuery in myRequest.responseText. Great!
Let us understand nitty gritty of few components in the above example.
Open method syntax
  • method: GET, POST
  • url: Location of API
  • async: True means asynchronous or false means synchronous
  • user: If API needs authentication
  • password: If API needs password
After open method is used we call send() to trigger the call at server but what if we change our code as below:
  1. varmyRequest = new XMLHttpRequest(); //myRequest is an object created by XHR API    
  2. console.log(typeof(myRequest)); // object    
  3. myRequest.open('GET','https://code.jquery.com/jquery-2.2.3.min.js');    
  4. myRequest.send();    
  5. console.log(myRequest.responseText); // may not get data in responseTextand there will be no error in console.   

What is the benefit of onreadystatechange after we called the send method?

The reason to use onreadystatechangeevent is to ensure data in responseText. To understand this, we will understand readyState property has different value between 0 to 4:
    0: Request not initialized
    1: Server connection established
    2: Request received
    3: Processing request
    4: Request finished and response is ready
To try this modify program like below
  1. varmyRequest = new XMLHttpRequest();    
  2. myRequest.onreadystatechange = function()    
  3. {    
  4.     switch (this.readyState)    
  5.     {    
  6.         case 0:    
  7.             console.log('request not initialized ');    
  8.             break;    
  9.         case 1:    
  10.             console.log('server connection established ');    
  11.             break;    
  12.         case 2:    
  13.             console.log('request received ');    
  14.             break;    
  15.         case 3:    
  16.             console.log('processing request ');    
  17.             break;    
  18.         case 4:    
  19.             console.log('request finished and response is ready ');    
  20.             console.log(myRequest.responseText);    
  21.             break;    
  22.     }    
  23. }    
  24. myRequest.open('GET''https://code.jquery.com/jquery-2.2.3.min.js');    
  25. myRequest.send();   
It has not printed “case 0: console.log('request not initialized ');” because when you create a new XHR request it states is already 0, so there is no change that is triggered.
Other Events
  • abort: To terminate XHR request if its sent
  • progress: You can monitor progress while the result is downloading
  • error: In case of any error generated
Other Properties
  • responseType: It could vary depending upon response sent by the server, ex- json, document, text, blob.
  • responseURL: This will be the final URL after redirects.
  • timeout: Number of milliseconds a request can take before terminating.
We understood one HTTP verb GET, the other common HTTP verb is POST. Posts  differentiate, as you are required to pass requestHeader depending upon request ex- you are submitting a form:
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Command-line utility

I am always excited to do things from the command line.

Is there a way we can leverage command-line utility to test?

Yes, use curl command. You can download curl utility and run it:
&I am saving in jQuery.js via redirection operator ‘>’. 
You can run VIM editor to review jQuery.js:
$ vi jQuery.js


I hope you enjoyed this article, the next article I will share more APIs. Please share your feedback/comments.