Friday, February 18, 2011

How to consume Web Service from JavaScript, Ajax and Web Servicer behavior


How to consume Web Service from JavaScript, Ajax and Web Servicer behavior

In my previous article I have already mentioned about how to create Web Service in .Net and consume that web service in ASP.Net.
Here I am going to show how to call Web Service from Java Script by referring to webservice.htc.
There are few different ways to call Web Service from Java Script, here I am using of webservice.htc to call Web Service.
First thing first, let us create Web Service which we will call from Java Script. I am going to use the same Web Service from my first article.  Here I will not going over the Web Service, as I have already have detailed information in my first blog.

A Web Service Example

In the following example we will use ASP.NET to create a simple Web Service that converts the temperature from Fahrenheit to Celsius, and vice versa:

The main line which needs to be uncommented out from the Web Service code is [System.Web.Script.Services.ScriptService] which will allow the web service to be accessed from JavaScript


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

[WebService(Namespace = "http://SampleWebservice.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

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

    [WebMethod]
    public int FahrenheitToCelsius(int far)
    {
        return ((((far) - 32) / 9) * 5);
    }

    [WebMethod]
    public int CelsiusToFahrenheit(int cel)
    {
        return ((((cel) * 9) / 5) + 32);
    }
   
}
This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web Services.

How to Call the Web Service from Web Service Behavior

Main point here is to consider is the reference of webservice.htc.  You can get more detail about webservice.htc here .
In below html file webservice.htc has been added to div tag using behavior attribute.  Using CallService method of webservicer, we can call the Web methods defined in ASP.Net web service. Calling web service return the result in XML Soap from which we can get the resulted data as shown below.

WebServiceCalling.htm
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 language="javascript" type="text/javascript">
     
            function useService(webService, WSDL, name) {
                var SSL = "";
                var protocol = window.document.location.protocol;
                var hostName = window.document.location.host;
                if (protocol == "https:") {
                    SSL = "SSL";
                }
                // Connect to the web service
                var string = parent.window.location.href.split("/");
                var virtual = string[3];
                webService.useService(protocol + "//" + hostName + "/" + virtual + "/" + WSDL + ".asmx?WSDL", name);
            }

            function doInit() {
                //Initialises web service
               
                useService(webServicer, "WebService", "WebService");
            }

            function convertFToC() {
                //Runs web service when select button event is fired
                var temp = document.getElementById("TempID").value;
                alert(temp);
                webServicer.WebService.callService(asynMessage, "FahrenheitToCelsius", temp);
            }

            function asynMessage(Result) {
                if (Result.error) {
                    var strMess = "Error During Web Service Call ";
                    try {
                        strMess += " - " + Result.errorDetail.raw.selectSingleNode("//mserror:description").text;
                        alert(strMess);
                    } catch (e) { ; }
                    return false;

                }
                document.getElementById("Result").value = Result.value;
               
            }
        
    script>
    <style type="text/css">
        .style1
        {
            width: 145px;
        }
    style>
head>

<body onload="doInit();">
<table border="1" cellspacing="5">
<tr>
<td class="style1">Temperature : td>
<td><input type="text" id="TempID" name="Temp" value="India" /> td>
<br />
tr>
<tr>
<td class="style1"> Result Mesage : td>
<td> <input type="text" id="Result" name="ResultName" /> td>
<br />
tr>
<tr>
<td colspan="2" align="center">
<button id="btnSubmit" type="button" onclick="convertFToC();" value="Show Result">Fahrenheit To Celsiusbutton> td>tr>
table>
 <div id="webServicer" style="behavior: url(webservice.htc)">div>
body>
html>

Output




How to Call WebService from Ajax

Ajax, Cool ha. ASP.Net has so many Ajax control now to work with Async. model. ScriptManager control is one to call the services (Web Services). It includes all what you want and just need to call the Web Service method after having reference to .asmx (ASP.net Web service).

I am using the same Web Service as defined above and use the ScriptManager from Ajax Toolkit to call the .asmx. Just Simple drag and drop the control to your .aspx page and set the service reference. In Code you will see below and how to call the web service method.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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 runat="server">
    <title>Calling Web Servicetitle>
    <script language="javascript" type="text/javascript">

        function onClick() {
            var temp = document.getElementById("TempID").value;
            var proxy = Service.FahrenheitToCelsius(temp, onSuccess, onFailure);
        }

        function onSuccess(sender, e) {
            document.getElementById("Result").value = sender;
        }

        function onFailure(sender, e) {
            alert("Problem retrieving XML data");
        }
       
    script>
head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="Service.asmx" />
            Services>
        asp:ScriptManager>
    div>
    <div>
        <table border="1" cellspacing="5">
            <tr>
                <td class="style1">
                    Temperature :
                td>
                <td>
                    <input type="text" id="TempID" name="Temp" value="45" />
                td>
                <br />
            tr>
            <tr>
                <td class="style1">
                    Result Mesage :
                td>
                <td>
                    <input type="text" id="Result" name="ResultName" />
                td>
                <br />
            tr>
            <tr>
                <td colspan="1" align="center">
                        <input type="button" value="Fahrenheit To Celsius" onclick="onClick();return false;" />
                td>
            tr>
        table>
       
    div>
    form>
body>
html>

Output



How to Call Web Service from JQuery  (Ajax)
Recently I started using JQuery (Java API Library) and found it has large variety of Java Script functions encapsulated to do job easy and fast. So thought to include how we can use JQuery to Access Web Service. I am using JQuery 1.5 which you can download from JQuery Site.
Below is the piece of code from Client Side, How to use JQuery. I am using the same web service from above, JQuery is all about the magic of ‘$’ and Selectors. JQuery has the Ajax capabilities to call/load the data Async.

Below code, I use the $.ajax to call the Web Service URL and pass the parameter to the Web method of web service, it return the success or failure as shown.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

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 runat="server">
    <title>title>
    <link href="Client/jquery-1.5.js" type="text/jscript" id="jquery"/>
    <script type="text/javascript" src="Client/jquery-1.5.js">script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#CalculateTemp").click(function (event) {
                getData();
            });
        });

        function getData() {
            var url1 = "Service.asmx/FahrenheitToCelsius";
            $.ajax({
                url: "Service.asmx/FahrenheitToCelsius",
                type:"POST",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                data:"{'far': '" + $('#TempID').val() + "'}",
                success:Result,
                error: AjaxFailed
        });
    }

    function Result(result) {
        $("#Result").val(result.d);
    }

    $(document).ready(function () {
        $("#sayHelloButton").click(function (event) {
            $.ajax(
            {
              type: "POST",
              url: "Service.asmx/HelloWorld",
              contentType: "application/json;charset=utf-8",
              dataType:"json",
              data: "{'message': '" + $('#name').val() + "'}",
              success:function(msg){
                AjaxSuccess(msg);
              },
             error: AjaxFailed
            });
        });
    });

 function AjaxSuccess(msg) {
     //$("#Result").val(msg.d);
        alert(msg.d);
    }
    function AjaxFailed(result) {
           alert(result.status + ' ' + result.statusText);
          } 
    script>
head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1> Calling ASP.NET AJAX Web Services with jQuery h1>
     Enter your name:
        <input id="name" />
        <br />
        <input id="sayHelloButton" value="Say Hello"
               type="button"  />
    div>
    <div>
        <table border="1" cellspacing="5">
            <tr>
                <td class="style1">
                    Temperature :
                td>
                <td>
                    <input type="text" id="TempID" name="Temp" value="45" />
                td>
                <br />
            tr>
            <tr>
                <td class="style1">
                    Result Mesage :
                td>
                <td>
                    <input type="text" id="Result" name="ResultName" />
                td>
                <br />
            tr>
            <tr>
                <td colspan="1" align="center">
                        <input type="button" value="Fahrenheit To Celsius" id="CalculateTemp"/>
                td>
            tr>
        table>
       
    div>
    form>
body>
html>

Output


Hope this will help for beginners and others to compare which one is more effective to there project based on there requirements. 

1 comment: