Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

My Friends

My Links

Permanent Posts

Portuguese Communities

Calling Web Service Methods Synchronously in ASP.NET AJAX

Update: I had forgot to send the code for the synchronous executor. Here it is, as an attachment. 

AJAX, standing for Asynchronous JavaScript and XML, is, well, asynchronous by default. Usually, that is exactly what we want, but there may be times when we want to execute some operation synchronously.

The ASP.NET AJAX (previously known as ASP.NET AJAX Extensions) allows us out of the box to call web service methods asynchronously. See this example:

... 

<script type="text/javascript">

function onAddSuccess(result, context, functionName)

{

    window.alert('Result: ' + result);

}

function onAddFailure(error, context, functionName)

{

    window.alert('Error: ' + error);

}

 </script>

... 

<asp:ScriptManager ID="ScriptManager" runat="server">

<Services>

<asp:ServiceReference Path="~/CalculatorService.asmx" />

</Services>

</asp:ScriptManager>

<asp:Button runat="server" ID="Button1" OnClientClick="CalculatorService.Add(1, 1, onAddSuccess, onAddFailure, null)" Text="Add 1 + 1" />

...

[ScriptService]

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class CalculatorService : WebService

{

[
ScriptMethod]

[WebMethod]

public Int32 Add(Int32 a, Int32 b)

{

return (a + b);

}

}

If all goes well, you would get the string "Result: 2" coming from the onAddSuccess callback function.

But in some cases, for example, an ASP.NET Custom Validator, you must get an answer immediately. Have a look at the following code:

function ExecuteSynchronously(url, method, args)

{

var executor = new Sys.Net.XMLHttpSyncExecutor();

// Instantiate a WebRequest.

var request = new Sys.Net.WebRequest();

// Set the request URL.

request.set_url(url + '/' + method);

// Set the request verb.

request.set_httpVerb('POST');

// Set request header.

request.get_headers()['Content-Type'] = 'application/json; charset=utf-8';

// Set the executor.

request.set_executor(executor);

// Serialize argumente into a JSON string.

request.set_body(Sys.Serialization.JavaScriptSerializer.serialize(args));

// Execute the request.

request.invoke();

if (executor.get_responseAvailable())

{

return (executor.get_object());

}

return (false);

}

function add()

{

var result = ExecuteSynchronously('CalculatorService.asmx', 'Add', { a: 1, b: 2 });window.alert('Result: ' + result);

}

<asp:Button runat="server" ID="Button1" OnClientClick="add()" Text="Add 1 + 1" />

You get the result immediately in the add method.

Bookmark and Share

Comments

rascunho » Blog Archive » links for 2009-03-06 said:

Pingback from  rascunho  &raquo; Blog Archive   &raquo; links for 2009-03-06

# March 6, 2009 3:10 PM

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# March 6, 2009 3:37 PM

Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-03-06 said:

Pingback from  Bruno Campagnolo de Paula weblog &raquo; Resumo do dia para 2009-03-06

# March 6, 2009 10:02 PM

עורכי דין said:

thanks i was looking for that code

# May 19, 2009 7:29 AM

Phani said:

Please give us solution  It is not working in FireFox

browser.

Regards

Phani kumar R.V

# September 4, 2009 11:13 AM

Ricardo Peres said:

Phani,

What is the error message or exception you are receiving?

# September 10, 2009 6:57 AM

Dilip kumar said:

The given example was very helpful to me

thnak u

# December 30, 2009 4:36 AM

YingqingTan said:

Very usefull thanks

# January 7, 2010 3:59 AM

Ram said:

Sys.Net.XMLHttpSyncExecutor object not found error got when i use the above code for calling webservice synchronously.

# January 11, 2010 3:21 PM

Ricardo Peres said:

Ram,

Did you include the .js file in my post's attached file (XMLHttpSyncExecutor.zip)?

# January 12, 2010 5:18 AM

cybersoftvn said:

When I pass Guid as parameter , it has problem with deserializing parameter to WebService.

# June 3, 2010 11:59 AM

Ricardo Peres said:

cybersoftvn:

That's because JSON does not support GUIDs, you'l have to use a String instead.

# June 3, 2010 4:59 PM

cybersoftvn said:

I change it to string and it works. Unfortunately, the data return is an instance of my defining class such as

class ABC { public string ID { get; set;} public string Name {get; set; } }

When I get data in this instance, I got undefined value.

What problem with it ? How to solve it ?

I dont got such problem when calling WebMethod using async way.

# June 5, 2010 12:48 PM

.NET Master said:

The reason that this does not work in FireFox is that FireFox does not call the onreadystatechange handler for an XmlHttpRequest that is synchronous.  To fix this problem, the following code needs to be added at the end of the Sys$Net$XMLHttpSyncExecutor$executeRequest function in XMLHttpSyncExecutor:

// fix for firefox bug

if (!this._responseAvailable && !this._timedOut && this._xmlHttpRequest.readyState === 4)

this._onReadyStateChange();

# August 15, 2010 8:07 AM

Ricardo Peres said:

.NET Master:

Thanks for your solution! I will update my post briefly.

RP

# August 15, 2010 6:05 PM

IrrerceGeld said:

I just book marked your blog on Digg and StumbleUpon.I enjoy reading your commentaries.

# October 30, 2010 7:02 PM

Ricardo Peres said:

# November 23, 2010 3:52 AM