Click here to Skip to main content
15,867,883 members
Articles / Programming Languages / Javascript
Tip/Trick

Synchronous and Asynchronous Web Service Invocation in Java script

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
6 Nov 2011CPOL1 min read 41.7K   10   1
How to call synchronous and asynchronous way web service method in JavaScript by using JSON
Introduction

In this article, I am going to explain synchronous and asynchronous web service method calls from client side(JavaScript) in ASP.NET and how to use them.


Synchronous vs. Asynchronous
In Synchronous call, if you are making any request, then you will have to wait till the response, you can't do any other thing until you will not get the response.

In Asynchronous call, if you are making any request, then you don't need to wait for the response and you can perform any other task. Whenever the response will come, you can receive in call back delegate.

So if any request will not take time, then you can use synchronous call else you can use asynchronous. Or if you are calling web service method in loop (like you want to do something in grid cell), then you will have to use synchronous way.

Now let's make a simple Webservice method. You will have to take care that you must uncomment the below line in your webservice as you are calling from JavaScript.
[System.Web.Script.Services.ScriptService]


C#
[WebMethod]
public string Test(string Name ) {
string sMessage= Name + " Today DateTime is " + DateTime.Now.ToShortDateString();
return sMessage;
}


Now let's create a common JavaScript method which will be used in sycnhronous call
C#
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");
}
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send(postData);
var responseText = xmlhttp.responseText;
return responseText;
}


You can write this method in .js file as well.
Below is the ASPX page code where I will call the JavaScript function on button click.
XML
<form id="form1" runat="server">
<input id="Button1" type="button" value="SyncCall" onclick="GetMessage()" />
<input id="Button2" type="button" value="AsyncCall" onclick="GetMessageByAsync()" />
<asp:TextBox ID="txtMessage" runat="server" Width="438px"></asp:TextBox>
</form>


In this code, there are 2 buttons, one will call GetMessage() JavaScript function and the other will call GetMessageByAsync().

Now I am writing the JavaScript functions as below:
C#
<script type="text/javascript">
function GetMessage() {
debugger;
var url = "WebService.asmx";
var result = GetSynchronousJSONResponse(url + '/Test', '{"Name": "Ram"}');
document.getElementById("<%= txtMessage.ClientID%>").value = eval('(' + result + ').d');
}
function GetMessageByAsync() {

$.ajax({
type: "POST",
url: "WebService.asmx/Test",
data: '{"Name": "Ram"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) { callback_response(res) },
error: function (res) { error_response(res) }
});
}
function callback_response(res) {
debugger;
document.getElementById("<%= txtMessage.ClientID%>").value = res.d;
}
function error_response(res) {
debugger;
alert(res);
}
< /script>


Here you can see in GetMessage() function that you will get response in same line but in
GetMessageByAsync(), you will get response in call back method like "Don’t call me, I will call you!".

For more details and code, see
http://stackdotnet.blogspot.com/2011/10/synchronous-and-asynchronous-web.html[^].

License

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


Written By
Architect Q3 technology
India India
Ram is .Net Architect by profession and passion having 8 year experience. He has extensive experience on Microsoft Development Platform and is also Microsoft Certified Application Developer (MCAD) for Web.
Reach me at rsharma@stackdotnet.com

http://www.stackdotnet.com/
6 Freely avaliable E-Books/

Comments and Discussions

 
GeneralReason for my vote of 5 Easy to follow, solves a common prob... Pin
App Software15-Feb-12 3:21
App Software15-Feb-12 3:21 

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.