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 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 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]
Example
In 1st example we will create XHR object and download jQuery by sending GET request,
- varmyRequest = new XMLHttpRequest();
- console.log(typeof(myRequest));
- myRequest.open('GET', 'https://code.jquery.com/jquery-2.2.3.min.js');
- myRequest.send();
- myRequest.onreadystatechange = function()
- {
- if (myRequest.readyState == 4 && myRequest.status == 200)
- {
- console.log(myRequest.responseText);
- }
Hence, we will get jQuery in myRequest.responseText. Great!
Let us understand nitty gritties of few components in 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:
- varmyRequest = new XMLHttpRequest();
- console.log(typeof(myRequest));
- myRequest.open('GET','https://code.jquery.com/jquery-2.2.3.min.js');
- myRequest.send();
- console.log(myRequest.responseText);
Question: What is the benefit of onreadystatechange after we called send method?
Answer: The reasons 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:
- varmyRequest = new XMLHttpRequest();
- myRequest.onreadystatechange = function()
- {
- switch (this.readyState)
- {
- case 0:
- console.log('request not initialized ');
- break;
- case 1:
- console.log('server connection established ');
- break;
- case 2:
- console.log('request received ');
- break;
- case 3:
- console.log('processing request ');
- break;
- case 4:
- console.log('request finished and response is ready ');
- console.log(myRequest.responseText);
- break;
- }
- }
- myRequest.open('GET', 'https://code.jquery.com/jquery-2.2.3.min.js');
- myRequest.send();
Output It has not printed “case 0: console.log('request not initialized ');” because when you create a new XHR request it’s state 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 result is downloading
- error: Incase 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.
- timout: Number of miliseconds a request can take before termintated.
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");
myRequest.send("fname=sumit&lname=jolly");
Command line utility
I am always excited to do things from command line.
Question: Is there a way we can leverage command line utilityto test?
Answer: Yes, use curl command. You can download curl utility and run it:
curlhttps://code.jquery.com/jquery-2.2.3.min.js
&I am saving in jQuery.js via redirection operator ‘>’.
You can run VIM editor to review jQuery.js:
$ vi jQuery.js
Summary
I hope you enjoyed this article, next article I will share more APIs. Please share your feedback/comments.