Click here to Skip to main content
15,881,754 members
Articles / Web Development / ASP.NET
Article

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 79.2K   346   33   15
Call an ASP.NET AJAX Webservice or page methods synchronously from client-side JavaScript to use in a custom validator.

Image 1

Introduction

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.

JavaScript
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");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
        // to be ensure non-cached version of response
    url = url + "?rnd=" + Math.random(); 
    
    xmlhttp.open("POST", url, false);//false means synchronous
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(postData);
    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.

JavaScript
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
}

Code-behind:

C#
[WebMethod]
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:

JavaScript
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
}

Code-behind:

C#
[WebMethod]
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.

JavaScript
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.NET
<asp:TextBox ID="txtCheckName" runat="server" Text="Validator"></asp:TextBox>
<asp:CustomValidator ID="cvName" ControlToValidate="txtCheckName"
                  ClientValidationFunction="CheckForDuplicateInDB" 
        EnableClientScript="true" runat="server" Display="Static"
                  ToolTip="Name is Duplicate." Text="*">
                           </asp:CustomValidator>
<asp:Button ID="btnClickMe" runat="server" Text="ClickMe!" />

Code-behind:

C#
//code behind
[WebMethod]
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:

JavaScript
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
    else
        alert(result.d); //process your result at client side
}

Code-behind:

C#
[WebMethod]
public string CallError()
{
    int i = 0;
    int j = 5 / i; //Devide by Zero Error
    return "Call Error";
}

References

History

  • 22 Oct 2008: Posted to The Code Project.

License

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


Written By
Web Developer Gateway Technolabs
India India
ASP.net C#, Microsoft Dynamics CRM 4.0

Comments and Discussions

 
GeneralWonderful Article - Minor Suggestion Pin
cjbarth10-May-11 8:28
cjbarth10-May-11 8:28 
GeneralMy vote of 5 Pin
Christian Del Bianco19-Apr-11 23:14
Christian Del Bianco19-Apr-11 23:14 
GeneralWeb Service Return List<> Pin
SSL SSL29-Nov-10 17:04
SSL SSL29-Nov-10 17:04 
GeneralThank's a lot Pin
andibaden29-Jan-10 9:39
andibaden29-Jan-10 9:39 
QuestionHow do I make a progress bar show when there is a synchronous ws call Pin
Travelthrprog11-Dec-09 11:26
Travelthrprog11-Dec-09 11:26 
Questionhow to call webservice using ajax from another machine Pin
gargprabhat20109-Oct-09 1:16
gargprabhat20109-Oct-09 1:16 
GeneralAsynchronous alternative for WebService-based validation Pin
CodeGolem2-May-09 2:45
CodeGolem2-May-09 2:45 
NewsASP.NET Synchronous Page Methods Pin
Eric Carter29-Oct-08 4:55
Eric Carter29-Oct-08 4:55 
GeneralRe: ASP.NET Synchronous Page Methods Pin
Sandip R Patel31-Oct-08 21:01
Sandip R Patel31-Oct-08 21:01 
GeneralRe: ASP.NET Synchronous Page Methods Pin
Eric Carter1-Nov-08 18:44
Eric Carter1-Nov-08 18:44 
GeneralRe: ASP.NET Synchronous Page Methods Pin
Sandip R Patel4-Nov-08 17:34
Sandip R Patel4-Nov-08 17:34 
GeneralRe: ASP.NET Synchronous Page Methods Pin
GeoffMci16-Apr-09 0:47
GeoffMci16-Apr-09 0:47 
Generalone important thing... Pin
NJoco27-Oct-08 22:31
NJoco27-Oct-08 22:31 
If you want to use this kind of WS call you must enable the POST and/or GET method in web.conig file.

<webservices>
<protocols>
<add name="HttpGet">
<add name="HttpPost">


GeneralRe: one important thing... Pin
Sandip R Patel31-Oct-08 20:53
Sandip R Patel31-Oct-08 20:53 
GeneralVery Nice Pin
Sam Shiles23-Oct-08 3:26
Sam Shiles23-Oct-08 3: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.