Month: February 2015

Service call using XMLHttpRequest Object in JavaScript

In the below post we are going to see how we can use browser XMLHttpRequest Object for sending and receiving the HTTP requests. This object was first implemented by Microsoft Internet explorer as an ActiveX object. Now it is native object of mostly all browser and because of common implementation it is identified as AJAX which is a way to send HTTP request without full page refresh. Lets explore this object.

For the example , I am going to call  Yahoo whether API. you can get this API description in the below Yahoo url

https://developer.yahoo.com/weather/

For the first step lets define the url in a JavaScript variable.

var url='https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';

Now lets create an object of XMLHttpRequest Object as below.

var xhr=new XMLHttpRequest();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Next we need to attach an event listener on “readystatechange” event of the xhr object. The xhr object have a property called “readyState” and whenever that property value change, the “readystatechange” event called. The possible value for this property is as below.

0- uninitialized

1-  loading

2- loaded

3- interactive

4- complete

below is the code which is checking “readyState” property on “readystatechange” event.

xhr.onreadystatechange=function()
    {
        if(xhr.status!==200 && xhr.status!==0)
        {
            console.log("Some error happen while executing request!");
            return;
        }
 
        if(xhr.readyState<4)
        {
            console.log(xhr.readyState);            
        }
        else
        {
            console.log(xhr.responseText);
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Next we need to call the open method of xhr object as below.

var isAsyncRequest=true;    
    xhr.open('GET',
            url,
            isAsyncRequest);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The first parameter is type of HTTP request, second is url and third specify whether the request type is async or sync.Now lets make the HTTP request using send method of xhr object as below.

xhr.send('');

Lets assemble these different pieces of code. The complete code will be as below.

function  whetherReport() {
        
    var url='https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
    var xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function()
    {
        if(xhr.status!==200 && xhr.status!==0)
        {
            console.log("Some error happen while executing request!");
            return;
        }
 
        if(xhr.readyState<4)
        {
            console.log(xhr.readyState);            
        }
        else
        {
            console.log(xhr.responseText);
        }
    }
    
    var isAsyncRequest=true;    
    xhr.open('GET',
            url,
            isAsyncRequest);
 
    xhr.send('');
 
}
whetherReport();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

below is the output which we get after executing above code in browser.

image

In the above post we explored how to use XMLHttpRequest object to make HTTP calls.

Hope you find this post useful. Thanks for reading . Happy Coding 🙂

Advertisements