Click here to Skip to main content
15,118,063 members
Articles / Web Development / ASP.NET
Posted 22 Oct 2008


33 bookmarked

Synchronous JavaScript call using Scriptable XML Webservice (S-AJAX)

Rate me:
Please Sign up or sign in to vote.
4.58/5 (15 votes)
4 Nov 2008CPOL2 min read
Call an ASP.NET AJAX Webservice or page methods synchronously from client-side JavaScript to use in a custom validator.

Image 1


This article shows how to consume a Microsoft AJAX web service (System.Web.Script.Services.ScriptService) to call synchronously at the client side using the XMLHttpRequest object and JavaScript.

Using a synchronous call, we can get rid of the problems of validating duplicate names in a custom validator without changing the code-behind. Many developers like me face this problem and have to find alternate solutions.

Using the Code

Here is the JavaScript code following the function GetSynchronousJSONResponse that calls the URL and posts the POST data synchronously using an XMLHttpRequest.

function GetSynchronousJSONResponse(url, postData) {
    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        // to be ensure non-cached version of response
    url = url + "?rnd=" + Math.random(); "POST", url, false);//false means synchronous
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    var responseText = xmlhttp.responseText;
    return responseText;

How to call GetSynchronousJSONResponse()

First, lets do a simple server call to get a single constant string. To understand the following code snippets, you need a bit of knowledge of JSON and how JSON represents an object. "HelloWorld" is the method name in the code-behind of the web service.

function HelloWorld() {
    var result = GetSynchronousJSONResponse(
                        '<%= Page.ResolveUrl("~/WebService.asmx/HelloWorld") %>', null);
                        //second argument is null as there is no argument in web method
    result = eval('(' + result + ')'); 
    alert(result.d); //process your result at client side


public string HelloWorld()
    return "Hello World";

In the above code, the eval() function parses the JSON string in to the JavaScript object.

Let's move to a bit more complex situation. If you want to pass data to the server and get the server to return processed data back to display to the user:

function HelloMe() {
    var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl(
                            "~/WebService.asmx/HelloMe") %>',
                          '{"Name":"' + document.getElementById('txtName').value + '"}');
    result = eval('(' + result + ')');
    alert(result.d); //process your result at client side


public string HelloMe(string Name)
    return "Hello " + Name + " !";

In the above code, if the input contains the name "Sandip", then the JSON string to post will be {"Name":"Sandip"}. Here, "Name" is an argument of the web method which is defined in the code-behind of the web service file. We can only use primitive data types like string, int, decimal, etc. We can also pass multiple arguments, for example, {"Name":"Sandip","Age":"23"}, to pass both the name and age.

Finally, let us use it in a custom validator. Here, the return type of the web method is bool according to the condition.

function CheckForDuplicateInDB(sender, arg) {
    var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl(
                          "~/WebService.asmx/CheckName") %>',
                       '{"Name":"' + arg.Value + '"}');
    result = eval('(' + result + ')');
    arg.IsValid = !result.d;

ASPX markup:

<asp:TextBox ID="txtCheckName" runat="server" Text="Validator"></asp:TextBox>
<asp:CustomValidator ID="cvName" ControlToValidate="txtCheckName"
        EnableClientScript="true" runat="server" Display="Static"
                  ToolTip="Name is Duplicate." Text="*">
<asp:Button ID="btnClickMe" runat="server" Text="ClickMe!" />


//code behind
public bool CheckName(string Name)
    // Checking for db records can be done here.
    return (Name == "Validator");

Additionally, here is the code to handle/display server side errors:

function CallError() {
    var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl(
             "~/WebService.asmx/CallError") %>', null);
    result = eval('(' + result + ')');
    if (typeof (result.d) == 'undefined')
        alert(result.Message);//you can also have StackTrace and ExceptionType
        alert(result.d); //process your result at client side


public string CallError()
    int i = 0;
    int j = 5 / i; //Devide by Zero Error
    return "Call Error";



  • 22 Oct 2008: Posted to The Code Project.


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


About the Author

Sandip R Patel
Web Developer Gateway Technolabs
India India C#, Microsoft Dynamics CRM 4.0

Comments and Discussions

GeneralWonderful Article - Minor Suggestion Pin
cjbarth10-May-11 9:28
Membercjbarth10-May-11 9:28 
GeneralMy vote of 5 Pin
Christian Del Bianco20-Apr-11 0:14
MemberChristian Del Bianco20-Apr-11 0:14 
GeneralWeb Service Return List<> Pin
SSL SSL29-Nov-10 18:04
MemberSSL SSL29-Nov-10 18:04 
GeneralThank's a lot Pin
andibaden29-Jan-10 10:39
Memberandibaden29-Jan-10 10:39 
QuestionHow do I make a progress bar show when there is a synchronous ws call Pin
Travelthrprog11-Dec-09 12:26
MemberTravelthrprog11-Dec-09 12:26 
Questionhow to call webservice using ajax from another machine Pin
gargprabhat20109-Oct-09 2:16
Membergargprabhat20109-Oct-09 2:16 
GeneralAsynchronous alternative for WebService-based validation Pin
CodeGolem2-May-09 3:45
MemberCodeGolem2-May-09 3:45 
NewsASP.NET Synchronous Page Methods Pin
Eric Carter29-Oct-08 5:55
MemberEric Carter29-Oct-08 5:55 
GeneralRe: ASP.NET Synchronous Page Methods Pin
Sandip R Patel31-Oct-08 22:01
MemberSandip R Patel31-Oct-08 22:01 
GeneralRe: ASP.NET Synchronous Page Methods Pin
Eric Carter1-Nov-08 19:44
MemberEric Carter1-Nov-08 19:44 
GeneralRe: ASP.NET Synchronous Page Methods Pin
Sandip R Patel4-Nov-08 18:34
MemberSandip R Patel4-Nov-08 18:34 
GeneralRe: ASP.NET Synchronous Page Methods Pin
GeoffMci16-Apr-09 1:47
MemberGeoffMci16-Apr-09 1:47 
Generalone important thing... Pin
NJoco27-Oct-08 23:31
MemberNJoco27-Oct-08 23:31 
GeneralRe: one important thing... Pin
Sandip R Patel31-Oct-08 21:53
MemberSandip R Patel31-Oct-08 21:53 
GeneralVery Nice Pin
Sam Shiles23-Oct-08 4:26
MemberSam Shiles23-Oct-08 4:26 

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.