Google
Web Netomatix

How to use JQuery to make async call in ASP.Net application

by Admin 20. July 2009 14:31

Download Sample Project

For one of my current project, I have been using ASP.Net AJAX to make async request into my ASP.Net to get some time related data. First, I am not a big fab of ASP.Net AJAX implementation. I will not go into debate on why. There are plenty of discussions on this topic. I will just spare myself from it. Second, the application was already using jQuery for other javascript related implementation. I was like, if we are already using jQuery why have an overhead of introducing Ajax tool kit. So I started porting the implementation to use jQuery. Through this series of posts, I will describe how you can use jQuery to make AJAX calls in ASP.Net applications. Well, the client side javascript can be used in any browser. So other than the server side implementation, there is no nothing specific to ASP.Net per se.

The sample project for these articles is a time synchronization service. The idea is that I want to display clock on the client machine that will display server time. Well you can say there is no big deal with that implementation. On page load, get the server time. Save in some client side variable and run one second timer on it. Well, that works for most part. There are situations where clients are behind really slow connections that can cause of lot latency in request and response. So in those cases, by the time your response gets to the client side, the server time that you returned to client is already behind by few seconds. For applications that has users who depend very heavily on this server time, this latency of few seconds can be very critical. In this first post I am not going to go into details of algorithm that I implemented to reduce this latency adjustment over time. This first sample does a very simple task. It sends asynchronous request to server every 10 seconds. The server returns its time and then client uses that to display clock.

Server Side Implementation

I have a class ClockData that has DataContract attribute set on it. You can pretty much figure out that I am planning on converting this service to WCF service and use the framework facilities to serialize and de-serialize data as well. So I am populating this class with three pieces of data (server time, latency and a cookie) and then using DataContractJsonSerializer class to serialize the data into JSON format and sending it to client.


private void SerializeServerClockData(ClockData data, Stream strm)
{
 var spSer =
   new DataContractJsonSerializer(typeof(ClockData));
 spSer.WriteObject(strm, data);
}

void SendResponse()
{
 long ms = (long)(_serverTime - new DateTime(1970, 1, 1)).TotalMilliseconds;
 var clockData = new ClockData()
  {ServerTime = ms.ToString(), Latency = _latency, ResponseKey = Guid.NewGuid().ToString("N")};
 Response.ContentType = "text/plain";
 Response.Expires = -1;
 Response.CacheControl = "no-cache";
 SerializeServerClockData(clockData, Response.OutputStream);
 Response.End();
}

From the code snippet above, you can see how plain and simple server side implementation is for this first sample. This will get little complicated as I get more into the actual algorithm of calculation of latency reduction.

Client Side Implementation

Since we are going to be using jQuery to make Ajax call, so we will need to include reference to jQuery javascript file. For this sample, I am going to show the AJAX request you can send using jQuery. The library has method named .getJSON that you can call to send the request. You can set the URL where request is to be sent, set the parameters that needs to be passed with request and set the callback function that should be called when request completes. It is that simple. Here is the implementation from the sample.


function getServerTime() {
 cTime = firstRequest ? -1 : curTime.getTime();
 $.getJSON(clockServiceUrl, { clientTime: cTime, requestKey: respKey }, gotServerTime);
}

function gotServerTime(data) {
 firstRequest = false;
 latency = data.Latency;
 curTime = new Date(parseInt(data.ServerTime));
 if (!clockTicking) createClockTimer();
 createServiceTimer(defaultServiceTimer);
}

function clockTick() {
 clockTicking = true;
 curTime.setTime(curTime.getTime() + 1000);
 elClockDisplay.text(curTime.toString());
 if (latency == -1)
 { elLatencyDisplay.text(""); }
 else
 {elLatencyDisplay.text(latency + " ms");}
}

$(function() {
 elClockDisplay = $('#clockDisplay');
 elLatencyDisplay = $('#latencyDisplay');
 getServerTime();
});

You can see with few lines of implementation you can use jQuery to make AJAX calls in ASP.Net application. In subsequent posts I will discuss how you can control the request little bit more instead of using .getJSON to use default settings.

Views: 4353

Tags: ,

ASP.Net | JQuery | AJAX

Comments

7/20/2009 3:14:12 PM #

trackback

Use jQuery in ASP.Net applications

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

10/28/2009 6:45:15 PM #

Cash Advance

I don't usually reply on articles I read but I have to say this was just great. Keep up the good work.

Cash Advance United States

11/11/2009 2:10:42 PM #

payday loans

Interesting ... as always - is your blog making any cash advance ? ;)

payday loans United States

11/25/2009 6:27:31 AM #

cash loans

Do you have any more info on this?

cash loans United States

12/10/2009 1:48:18 AM #

payday loans

Yea nice Work !:D

payday loans United States

12/21/2009 7:44:03 AM #

Massachusetts Payday Loans

Do you make money out of this blog? just curious

Massachusetts Payday Loans United States

12/30/2009 9:57:33 AM #

payday loans

Yea nice Work !:D

payday loans United States

1/2/2010 4:06:11 AM #

faxless payday loans

Do you make money out of this blog? just curious

faxless payday loans United States

1/18/2010 1:48:53 PM #

payday loans

If you want to be successful, find someone who has achieved the results you want and copy what they do and you'll achieve the same results.

payday loans United States

2/4/2010 5:11:42 AM #

ucvhost

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

ucvhost United States

2/6/2010 7:23:02 AM #

ucvhost

How to use Remote Desktop Connection for the two systems which have same IP Address?

ucvhost United States

2/10/2010 8:52:18 AM #

25th Wedding Anniversary

I am so glad i came across this post for I now know how to use JQuery to make async call in ASP.Net application. Thank you so much for your time & efforts.

25th Wedding Anniversary United States

2/10/2010 10:47:45 PM #

Horse Saddles

Thank you so much for sharing this post. It has been really helpful.

Horse Saddles

2/11/2010 12:13:43 AM #

Credit Cards

This was an excellent read. Thanks for sharing.

Credit Cards United States

2/11/2010 12:24:32 AM #

Non Chexsystems Banks

I appreciate you providing the sample project download link. It was much easier to understand it.

Non Chexsystems Banks United States

7/22/2010 12:32:04 AM #

Overnight Printing

Thank you so much for sharing this post. It has been really helpful.

Overnight Printing United States