Click here to Skip to main content
13,248,369 members (39,139 online)
Click here to Skip to main content
Add your own
alternative version


70 bookmarked
Posted 17 Aug 2007

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


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.


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:


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:

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:

            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" 

                       System.Web.Extensions, Version=1.0.61025.0, 
                       Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

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:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">

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:

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

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,
function OnComplete(arg)
function OnTimeOut(arg)
    alert("timeOut has occured");
function OnError(arg)
    alert("error has occured: " + arg._message);
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
<input type="text" value="" id="MyTextBox" />
<input type="button" value="Send Request to the Web Service" 

       id="RequestButton" onclick="return SendRequest()" />

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


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.


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


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


About the Author

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

You may also be interested in...


Comments and Discussions

QuestionGetting Error: The server method "Method_Name" failed Pin
Member 1153120216-Mar-15 22:26
memberMember 1153120216-Mar-15 22:26 
GeneralMy Vote of 5 Pin
DivyaNaidu48629-Oct-14 23:01
memberDivyaNaidu48629-Oct-14 23:01 
QuestionThanks! Pin
Member 83389719-Oct-12 4:53
memberMember 83389719-Oct-12 4:53 
GeneralMy vote of 5 Pin
Mehdi_Csharp12-Aug-11 9:48
memberMehdi_Csharp12-Aug-11 9:48 
GeneralMy vote of 5 Pin
Monjurul Habib2-Mar-11 8:50
memberMonjurul Habib2-Mar-11 8:50 
GeneralThanx Pin
shakesperoo3@hotmail.com21-Oct-10 0:32
membershakesperoo3@hotmail.com21-Oct-10 0:32 
QuestionHow to secure the web service Pin
Tomz_KV23-Sep-10 5:04
memberTomz_KV23-Sep-10 5:04 
GeneralMySampleService not defined Pin
Member 44580097-Aug-08 8:38
memberMember 44580097-Aug-08 8:38 
GeneralRe: MySampleService not defined Pin
Joseph Foster15-Apr-10 7:47
memberJoseph Foster15-Apr-10 7:47 
Generalnot working in mozilla Pin
pravin parmar16-Dec-07 3:42
memberpravin parmar16-Dec-07 3:42 
GeneralRe: not working in mozilla Pin
aprasp6-Nov-09 10:07
memberaprasp6-Nov-09 10:07 
QuestionHelp me ... Pin
Patel Maulik11-Dec-07 2:36
memberPatel Maulik11-Dec-07 2:36 
GeneralThanks for doing! But... Pin
details@insidespirit.com1-Nov-07 15:57
memberdetails@insidespirit.com1-Nov-07 15:57 
AnswerRe: Thanks for doing! But... Pin
semenoff1-Nov-07 21:06
membersemenoff1-Nov-07 21:06 
GeneralRe: Thanks for doing! But... Pin
details@insidespirit.com2-Nov-07 2:42
memberdetails@insidespirit.com2-Nov-07 2:42 
AnswerRe: Thanks for doing! But... Pin
semenoff4-Nov-07 21:40
membersemenoff4-Nov-07 21:40 
GeneralHi Pin
sacheen198413-Oct-07 2:53
membersacheen198413-Oct-07 2:53 
AnswerRe: Hi Pin
semenoff13-Oct-07 2:56
membersemenoff13-Oct-07 2:56 
QuestionHi Pin
buddhie3-Oct-07 18:26
memberbuddhie3-Oct-07 18:26 
AnswerRe: Hi Pin
semenoff6-Oct-07 11:32
membersemenoff6-Oct-07 11:32 
Generalgood effort Pin
MD. A ISLAM9-Sep-07 6:34
memberMD. A ISLAM9-Sep-07 6:34 
GeneralRe: good effort Pin
semenoff9-Sep-07 6:51
membersemenoff9-Sep-07 6:51 
GeneralExternal Web Service Pin
Singh Saab23-Aug-07 5:50
memberSingh Saab23-Aug-07 5:50 
GeneralRe: External Web Service Pin
semenoff23-Aug-07 10:21
membersemenoff23-Aug-07 10:21 
GeneralPerfect!!! Pin
soft_yahoo22-Aug-07 22:40
membersoft_yahoo22-Aug-07 22: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 9 Sep 2007
Article Copyright 2007 by semenoff
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid