Sunday 20 October 2013

Call a WebService using Javascript with complex return Type.

In this article we are going to see how to call a WebService using Javascript and get the result from the service which is a complex type Employee.

complex Return Type :

Create a Form Which will get the employee name from the textbox and pass as parameter to the Web Service. Web Service return a Complex Employee object which is unknown to javascript to identitfy.
Javascript knows only as it is a object.

Javascript :

 Now we are going to initialize a correct object for the XMLHTTPRequest then form the Url from the Page.ResolveUrl method which will resolve the path of the web service present inside the project.
then Call the method open from the XmlHttp which have to pass the url and mention the Post as method

Set the Request Header "Content-Type" as "Json" ,Use the Send Method to send the Request if any parameter is need to send then send as parameter inside the Send Method in Json format.

Json Format :

{
"employees": [
{ "firstName":"Purushoth" , "lastName":"Kumar" }, 
{ "firstName":"Anna" , "lastName":"Larsen" }, 
{ "firstName":"Suresh" , "lastName":"Kanna" }
]
}

Output Form:


Result :





Javascript :


<script type="text/javascript" language="javascript">
        function Call() {
            var XmlHttp = null;
            if (window.XMLHttpRequest) {
                XmlHttp = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                if (new ActiveXObject("Microsoft.XMLHTTP")) {
                    XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    else
                    {
                        XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                    }           
            }

                var url = '<%= Page.ResolveUrl("~/Calc.asmx/Hello") %>';
                  url = url+ '?rnd='+Math.random();
               
            XmlHttp.open("POST", url, false);
            XmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            XmlHttp.send('{"name":"' + document.getElementById("txt").value + '"}');
            var reply = XmlHttp.responseText;
            var value = eval('(' + reply + ')');
            alert(value.d.Id +' :'+  value.d.Name);

        }
    </script>



Aspx Code:
<body>
    <form id="form1" runat="server">
    <div style="vertical-align:top" align="center">
    <fieldset align="center" style="width:300Px">
    <legend>Employee Form</legend>
    Name :
    <input name="txt" id="txt" type="text"" />
    <a  href="javascript:Call()">Async Call</a>
    </fieldset>
    </div>
    </form>
</body>


Service Code :


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

namespace WebApplication7
{
    /// <summary>
    /// Summary description for Calc
    /// </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 Calc : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public Employee Hello(string name)
        {
            return new Employee() { Id = 1, Name = name };
        }
    }

    public class Employee
    {
        public string Name { set; get; }

        public int Id { set; get; }
    }
}




From this article you can learn how to call a web service using Javascript and read the value from the return value of service even though it is an object type .

No comments:

Post a Comment