Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 9 Sep 2007
Rate this:
Please Sign up or sign in to vote.
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:

[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:

[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:

<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:

<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:

<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:

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:

<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)

Share

About the Author

semenoff
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

 
QuestionThanks! PinmemberMember 83389719-Oct-12 3:53 
GeneralMy vote of 5 PinmemberMehdi_Csharp12-Aug-11 8:48 
GeneralMy vote of 5 PinmemberMonjurul Habib2-Mar-11 7:50 
GeneralThanx Pinmembershakesperoo3@hotmail.com20-Oct-10 23:32 
QuestionHow to secure the web service PinmemberTomz_KV23-Sep-10 4:04 
Generalnot working in mozilla Pinmemberpravin parmar16-Dec-07 2:42 
GeneralRe: not working in mozilla Pinmemberaprasp6-Nov-09 9:07 
QuestionHelp me ... PinmemberPatel Maulik11-Dec-07 1:36 
GeneralThanks for doing! But... Pinmemberdetails@insidespirit.com1-Nov-07 14:57 
AnswerRe: Thanks for doing! But... Pinmembersemenoff1-Nov-07 20:06 
GeneralRe: Thanks for doing! But... Pinmemberdetails@insidespirit.com2-Nov-07 1:42 
AnswerRe: Thanks for doing! But... Pinmembersemenoff4-Nov-07 20:40 
GeneralHi Pinmembersacheen198413-Oct-07 1:53 
AnswerRe: Hi Pinmembersemenoff13-Oct-07 1:56 
QuestionHi Pinmemberbuddhie3-Oct-07 17:26 
AnswerRe: Hi Pinmembersemenoff6-Oct-07 10:32 
Generalgood effort PinmemberMD. A ISLAM9-Sep-07 5:34 
GeneralRe: good effort Pinmembersemenoff9-Sep-07 5:51 
GeneralExternal Web Service PinmemberSingh Saab23-Aug-07 4:50 
GeneralRe: External Web Service Pinmembersemenoff23-Aug-07 9:21 
GeneralPerfect!!! Pinmembersoft_yahoo22-Aug-07 21:40 
GeneralThanks! PinmemberBPloe21-Aug-07 3:37 
GeneralRe: Thanks! Pinmembersemenoff21-Aug-07 7:21 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 9 Sep 2007
Article Copyright 2007 by semenoff
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid