pavanarya

Let us share the knowledge

Calling a Web Service from Javascript using XMLHttpRequest

with 6 comments

Hi in this post i want to write about calling a web service from plain javascript using XMLHttpRequest in a html or asp.net file.
Actually there are number of ways for calling a web service. We can make use of Jquery, YUI or else we can also make use of Ajax tool kit provided by microsoft.
You can see my previous post that makes use of ScriptManager class provided by Microsoft .Net Framework to call web services from javascript.

Using XMLHttpRequest to call web services from javascript

First of all let us create a simple web service using .Net Framework and visual studio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace SOAPHEADEREXAMPLE
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World pavan";
        }
        [WebMethod]
        public string AddResults(string a,string b)
        {
            int addResult = Convert.ToInt32(a) + Convert.ToInt32(b);
            return addResult.ToString();
        }
    }
}

Now let us compile the web service and browse it using this url

 

http://localhost:1525/WebService1.asmx?op=HelloWorld

Now we can see soap request and response formats in browser
Soap Request Format

POST /WebService1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/HelloWorld"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <HelloWorld xmlns="http://tempuri.org/" />
  </soap:Body>
</soap:Envelope>

Soap request xml has 3 main parts
1.Envelope(root tag)
2.Header node
3.Body node

Header node is optional and can have some data which is either specific to the service or not specific to the service.

Body node is a compulsory node and it contains the information related to the web method.

Soap Response Format

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <HelloWorldResponse xmlns="http://tempuri.org/">
      <HelloWorldResult>string</HelloWorldResult>
    </HelloWorldResponse>
  </soap:Body>
</soap:Envelope>

Calling Web Service from JavaScript Using XMLHttpRequest

1.First create an object of XMLHttprequest

       var xmlHTTP ;
         if (window.XMLHttpRequest) {
        xmlHTTP= new window.XMLHttpRequest;//For browsers other than ie
    }
    else {
        try {
            xmlHTTP= new ActiveXObject("MSXML2.XMLHTTP.3.0"); //for ie
        }
        catch(ex) {
            
        }
    }

2. Now set the web service url using the open method of XMLHttprequest.
Open method takes 5 parameters
1.Type of HTTPMethod
2.Url
3. Boolean value that specifies async or not
4,5. Username and password. These are used for user authentication and they are optional

xmlHTTP.open ("POST", "http://localhost:1525/WebService1.asmx",true);

3. Now set the request headers using the method setRequestHeaders

xmlHTTP.setRequestHeader( "Content-Type","text/xml; charset=utf-8");
xmlHTTP.setRequestHeader(
"SOAPAction", "http://tempuri.org/HelloWorld");

Note: we are supposed to set SOAPAction to http://tempuri.org/HelloWorld otherwise it will throw an error
(HelloWorld is the method that we are trying to access)

4. Now create the soap request xml string.

strRequest = "<?xml version='1.0' encoding='utf-8'?>";
        strRequest = strRequest + "<soap:Envelope " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
        strRequest = strRequest + " <soap:Body>";
        strRequest = strRequest + "<HelloWorld xmlns='http://tempuri.org/' />";
        strRequest = strRequest + "</soap:Body>";
        strRequest = strRequest + "</soap:Envelope>";

The above xml should be same as the soap request xml mentioned above under the title Soap request format.

5. Now create the code that is supposed to be executed after receiving the response from web service.
This comes into picture only when async is set to true in the method XMLHttpRequest.open()

xmlHTTP.onreadystatechange = function () {
    if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
        alert(xmlHTTP.responseXML.xml);
    }
}
Different value for readystate
0--Uninitialized
1--Loading
2--loaded(but data not recieved)
3--Interactive--Some part of the data is recieved
4--Completed(all data recieved)

//So in the above code once data is completely received from web service then alert is called.

6. Calling the send method .This method actually calls the web service

xmlHTTP.send(strRequest);

Complete html page for calling a method that has no parameters

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" >

        var xmlHTTP ;
         if (window.XMLHttpRequest) {
        xmlHTTP= new window.XMLHttpRequest;
    }
    else {
        try {
            xmlHTTP= new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            
        }
    }
xmlHTTP.open ("POST", "http://localhost:1525/WebService1.asmx",
true);
xmlHTTP.setRequestHeader( "Content-Type","text/xml; charset=utf-8");
xmlHTTP.setRequestHeader(
"SOAPAction", "http://tempuri.org/HelloWorld");


strRequest = "<?xml version='1.0' encoding='utf-8'?>";
        strRequest = strRequest + "<soap:Envelope " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
        strRequest = strRequest + " <soap:Body>";
        strRequest = strRequest + "<HelloWorld xmlns='http://tempuri.org/' />";
        strRequest = strRequest + "</soap:Body>";
        strRequest = strRequest + "</soap:Envelope>";


xmlHTTP.onreadystatechange = function () {
    if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
        alert(xmlHTTP.responseXML.xml);
    }
}
xmlHTTP.send(strRequest);

//alert(xmlHTTP.responseXML.xml);
//var resp = unescape(xmlHTTP.responseXML.xml);
    </script>
</head>
<body>

</body>
</html>

Complete html page for calling a method that has Parameters

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" >

        var xmlHTTP;
        if (window.XMLHttpRequest) {
            xmlHTTP = new window.XMLHttpRequest;
        }
        else {
            try {
                xmlHTTP = new ActiveXObject("MSXML2.XMLHTTP.3.0");
            }
            catch (ex) {

            }
        }
        xmlHTTP.open("POST", "http://localhost:1525/WebService1.asmx",true);
        xmlHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlHTTP.setRequestHeader(
"SOAPAction", "http://tempuri.org/AddResults");

        strRequest = "<?xml version='1.0' encoding='utf-8'?>";
        strRequest = strRequest + "<soap:Envelope " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
        strRequest = strRequest + " <soap:Body>";
        strRequest = strRequest + "<AddResults xmlns='http://tempuri.org/'><a>10</a><b>20</b></AddResults>";
        strRequest = strRequest + "</soap:Body>";
        strRequest = strRequest + "</soap:Envelope>";


        xmlHTTP.onreadystatechange = function () {
            if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
                alert(xmlHTTP.responseXML.xml);
            }
        }
        xmlHTTP.send(strRequest);

        //alert(xmlHTTP.responseXML.xml);
        //var resp = unescape(xmlHTTP.responseXML.xml);
    </script>
</head>
<body>

</body>
</html>

Limitations of XMLHttpRequest
1. We cannot make cross domain calls using XMLHttpRequest. This is because of browsers security policies.
2. We cannot transmit files using this.
3.Multiple request cannot be sent in a sequence
4. Also the order of data received from different request will not be in same order.

About these ads

Written by pavanarya

May 20, 2012 at 6:19 pm

6 Responses

Subscribe to comments with RSS.

  1. This was really helpful to me while i wrote my first program like this.

    Madhava

    May 28, 2013 at 9:35 pm

    • Thanks Madhav, I am glad that it helped you :)

      pavanarya

      May 30, 2013 at 8:31 am

      • Hello, I would like to know if the server side can be implemented also in JavaScript and how it would be?.
        I would like to introduce one system with both server side and also some request to other servers in an embedded system.

        Ipar

        October 2, 2013 at 8:18 pm

      • Hi Ipar,
        Sorry i am not clear about your requirement… So if possible can you please elaborate your requirement and send me a mail…
        My mail id : pavan.aryasomayajulu@gmail.com

        Thanks,
        Pavan

        pavanarya

        October 12, 2013 at 9:10 am

  2. thx pavanarya, it helped me alot !!
    i use the code of : calling a method that has no parameters, when i put this instruction : alert(xmlHTTP.responseXML.xml); it returns to me the Soap Response Format it self, so how can i get the HelloWord string from the server whithout the xml code , is there an other method for this ?
    thx

    ichraf

    July 6, 2013 at 4:20 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 67 other followers

%d bloggers like this: