Click here to Skip to main content
15,880,796 members
Articles / Web Development / HTML

How to call a Web Service from client-side JavaScript using ASP.NET AJAX

Rate me:
Please Sign up or sign in to vote.
4.68/5 (22 votes)
9 Sep 2007CPOL4 min read 236.7K   3.2K   70   27
The ASP.NET AJAX framework provides us with an easy and elegant way to consume Web Services. This article concentrates on the basics of client-side JavaScript calls made to Web Services.

Calling Web Service from client-side JavaScript.gif

Introduction

The ASP.NET AJAX framework provides us with an easy and elegant way to consume Web Services from client-side JavaScript code. In fact, it is even easier to write a simple AJAX enabled Web Service and connect to it from client-side JavaScript than it is to write an article like this one. In this article, I have tried to collect some of my experiences which I hope can be useful for you to get started with using the ASP.NET AJAX technology in general and ASP.NET AJAX enabled Web Services in particular.

Background

Some time ago, I was looking for a possibility to dynamically update some parts of my page without refreshing the rest of it. In fact, I only needed to update some small text fields on my page. Apart from this text, my page had a lot of graphics on it, and it was a bit irritating for users to watch the whole page flashing while those text fields were updated. So, I had to avoid refreshing the graphics on the page while updating my text data. The ASP.NET AJAX technology has shown to be the perfect choice for this purpose. It is possible to use different AJAX techniques to achieve this kind of behaviour, for example: partial page updates, page methods, and Web Service calls. In this article, I will try to cover the Web Service approach.

Installing ASP.NET AJAX

Well, first of all, to get started, you will have to install the ASP.NET AJAX framework. You can do the first step by visiting AJAX: The Official Microsoft ASP.NET 2.0 Site. There, you can find links and pretty good instructions on how to install and get started with ASP.NET AJAX. I am using ASP.NET AJAX version 1.0 while writing this article.

Creating an AJAX Enabled Web Service

Let us assume that you managed to install the ASP.NET AJAX framework. We can now start with creating a new AJAX enabled Web application:

Screenshot - New AJAX Enabled Web Application

What we need now is the AJAX enabled Web Service. Let us add a new Web Service called MySampleService to the project:

Screenshot - Add New Web Service

In order to AJAX enable it, we will have to add the following attribute to the Web Service declaration part:

C#
[System.Web.Script.Services.ScriptService()]

When this is done, our Web Service is ready to respond to client-side JavaScript calls. One more thing has to be done here: we need the Web Method that we will call from client-side JavaScript. Let us define it like this:

C#
[WebMethod]
public string GetServerResponse(string callerName)
{
    if(callerName== string.Empty)
        throw new Exception("Web Service Exception: invalid argument");

    return string.Format("Service responded to {0} at {1}", 
                         callerName, DateTime.Now.ToString());
}

Configuring the ASP.NET Application

The ASP.NET application's web.config file also has to be modified in order to enable Web Service calls from client-side JavaScript code.

This modification is made for you by Microsoft Visual Studio 2005 if you are using the ASP.NET AJAX template. Here is an example of what can be inserted into the httpHandlers section of your web.config file:

XML
<configuration>
    ...
    <system.web>
        ...
        <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" 
                 type="System.Web.Script.Services.ScriptHandlerFactory, 
                       System.Web.Extensions, Version=1.0.61025.0, 
                       Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            ...
        </httpHandlers>
        ...
    </system.web>
    ...
<configuration>

Making Client-side JavaScript Code

Let us take a look at the default.aspx file that was automatically created in our project (if it was not - then you will have to add one manually). First, we have to make sure that we have one and only one instance of the ScriptManager object on our page:

XML
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div></div>
</form>
</body>

Then, we have to add a Services collection to our ScriptManager object, add a ServiceReference to the Services collection, and specify the Path to the desired service. The result might look like this:

ASP.NET
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
</Services>
</asp:ScriptManager>
<div></div>
</form>
</body>

or like this, if you prefer to do it directly in your code-behind file:

C#
ScriptManager1.Services.Add(new ServiceReference("~/WebServices/MyWebService.asmx"));

Now, we need some client-side functions, a button to trigger the Web Service request, and a text box to provide the input for the Web Service:

  • SendRequest - this function will send an asynchronous request to the Web Service
  • OnComplete - this function will receive the result from the Web Service
  • OnError - this function will be triggered if an error occurs while executing the Web Service
  • OnTimeOut - this function will be triggered if the Web Service will not respond
  • MyTextBox- the ext box with the input for the Web Service
  • RequestButton - the button that triggers the SendRequest function

The result might look like this:

ASP.NET
<head runat="server">
<title>Web Service call from client-side JavaScript</title>
<script language="javascript" type="text/javascript">
function SendRequest() 
{
    MySampleService.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError,
    OnTimeOut);
}
function OnComplete(arg)
{
    alert(arg);
}
function OnTimeOut(arg)
{
    alert("timeOut has occured");
}
function OnError(arg)
{
    alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="text" value="" id="MyTextBox" />
<input type="button" value="Send Request to the Web Service" 
       id="RequestButton" onclick="return SendRequest()" />
</div>
</form>
</body>

This is basically it. You have a functioning client-side JavaScript code that calls a server-side Web Service and treats the returned response. If we supply an empty input value to the GetServerResponse method of MySampleService, then as expected, it will throw an exception. This exception will be caught by the OnError function in the client-side JavaScript:

Screenshot - Web Service Exception

Conclusion

The described client-to-server communication model where the client-side JavaScript code invokes the Web Service methods provides us with a lot of flexibility to extend our website functionality. At the same time, the traffic is minimal: we send only the input data required by the Web Method, and we receive only the return value from the method being invoked.

History

You can always find the most up-to-date version of this article in the AJAX section of my website.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Kraftvaerk a/s
Denmark Denmark
I graduated from Saint Petersburg Electrotechnical University, Russia in 1997 with specialty in Microelectronics.

I always had a grate deal of interest for programming. Through years of working first as a software developer in cowex a/s - Industrial Automation company and later as a Senior Consultant in Kraftavaerk a/s I achieved a lot of experiences with Delphi, VB, JavaScript and SQL.

Since 2006, I started paying more attention to .Net technologies and especially C# programming language.

More information about me and my projects is available at my .Net programming web site

Comments and Discussions

 
QuestionGetting Error: The server method "Method_Name" failed Pin
Member 1153120216-Mar-15 21:26
Member 1153120216-Mar-15 21:26 
GeneralMy Vote of 5 Pin
DivyaNaidu48629-Oct-14 22:01
DivyaNaidu48629-Oct-14 22:01 
QuestionThanks! Pin
Member 83389719-Oct-12 3:53
Member 83389719-Oct-12 3:53 
GeneralMy vote of 5 Pin
User 742743512-Aug-11 8:48
User 742743512-Aug-11 8:48 
GeneralMy vote of 5 Pin
Monjurul Habib2-Mar-11 7:50
professionalMonjurul Habib2-Mar-11 7:50 
GeneralThanx Pin
shakesperoo3@hotmail.com20-Oct-10 23:32
shakesperoo3@hotmail.com20-Oct-10 23:32 
QuestionHow to secure the web service Pin
Tomz_KV23-Sep-10 4:04
Tomz_KV23-Sep-10 4:04 
GeneralMySampleService not defined Pin
Member 44580097-Aug-08 7:38
Member 44580097-Aug-08 7:38 
GeneralRe: MySampleService not defined Pin
Joseph Foster15-Apr-10 6:47
Joseph Foster15-Apr-10 6:47 
Generalnot working in mozilla Pin
pravin parmar16-Dec-07 2:42
pravin parmar16-Dec-07 2:42 
GeneralRe: not working in mozilla Pin
AprNgp6-Nov-09 9:07
AprNgp6-Nov-09 9:07 
QuestionHelp me ... Pin
Patel Maulik11-Dec-07 1:36
Patel Maulik11-Dec-07 1:36 
GeneralThanks for doing! But... Pin
details@insidespirit.com1-Nov-07 14:57
details@insidespirit.com1-Nov-07 14:57 
AnswerRe: Thanks for doing! But... Pin
semenoff1-Nov-07 20:06
semenoff1-Nov-07 20:06 
GeneralRe: Thanks for doing! But... Pin
details@insidespirit.com2-Nov-07 1:42
details@insidespirit.com2-Nov-07 1:42 
AnswerRe: Thanks for doing! But... Pin
semenoff4-Nov-07 20:40
semenoff4-Nov-07 20:40 
GeneralHi Pin
sacheen198413-Oct-07 1:53
sacheen198413-Oct-07 1:53 
AnswerRe: Hi Pin
semenoff13-Oct-07 1:56
semenoff13-Oct-07 1:56 
QuestionHi Pin
buddhie3-Oct-07 17:26
buddhie3-Oct-07 17:26 
AnswerRe: Hi Pin
semenoff6-Oct-07 10:32
semenoff6-Oct-07 10:32 
Generalgood effort Pin
MD. A ISLAM9-Sep-07 5:34
MD. A ISLAM9-Sep-07 5:34 
GeneralRe: good effort Pin
semenoff9-Sep-07 5:51
semenoff9-Sep-07 5:51 
GeneralExternal Web Service Pin
Singh Saab23-Aug-07 4:50
Singh Saab23-Aug-07 4:50 
The example you provided assumes that the web service lives on the same server as the caller, hence the ability to reference the web service via a relative path:

ScriptManager1.Services.Add(new ServiceReference("~/WebServices/MyWebService.asmx"));

What if the web service was on a different server or some place where the caller didn't know. We would then need a discovery file method of loading the web service. Can you give us an example of how to do this?

Thanks!
GeneralRe: External Web Service Pin
semenoff23-Aug-07 9:21
semenoff23-Aug-07 9:21 
GeneralPerfect!!! Pin
soft_yahoo22-Aug-07 21:40
soft_yahoo22-Aug-07 21:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.