Google
Web Netomatix

Insert new elements in reverse order using jQuery

by Admin 28. July 2009 06:28

prepend enries using jquery

I have been extending the current sample clock synchronization application to add some more features to show more capabilities of jQuery. In the last update I added functionality to display latency numbers when service was called every X number of minutes. If you will let the page running for quite some time you will see how quickly the entries get appended to the display. What we really want is that latest entries should be displayed at the top. So basically instead of appending the new entries, we want to prepend the new entry to the last entry added. We are in luck here. jQuery does offer couple of methods here that makes it easy. prepend, prependTo, before, insertBefore methods are your friend here. It turns out that all these methods get mapped to one function behind the scene, insertBefore. Following code snippet from the application shows entries are added in reverse order.


var elLastLatencyEntry;
var elLastMessageEntry;

function displayLatency() {
 var elToAppend = null;
 if (latency == -1) { elToAppend = $("<p>Initializing</p>"); }
 else { elToAppend = $("<p>" + latency + " ms</p>"); }
 if (null == elLastLatencyEntry)
 { elLastLatencyEntry = elToAppend.appendTo(elLatencyDisplay); }
 else { elLastLatencyEntry = elToAppend.prependTo(elLastLatencyEntry); }
}

You can see from the code that I save the last entry that was added in a variable for later use. This avoids over head of finding the latest entry again and again every X number of seconds.

Views: 1678

Tags: , ,

AJAX | JavaScript | JQuery

How to modify default behavior of getJSON or other jQuery AJAX requests

by Admin 24. July 2009 08:14

In my previous posts How to serialize AJAX requests and others, I have been using simple jQuery method .getJSON to get response from server. You can see that this method takes only 3 parameters and there is not much you have to set or do to set up your AJAX calls and it works for 90% of the cases. But some time you run into situation where you need little bit more control on how the request is set up or want to control the request a little bit. jQuery does provide you excess to underlying structures to set some parameters for the calls or you can use the low level .ajax. A lot of time you really are not looking to use .ajax function but you want to set some default behavior for all the AJAX requests that are being send using .getJSON. To do that you can use .ajaxSetup method. This function has one parameter where you can set up all the AJAX call parameters in a structure. For example in my application, I want to make sure that all AJAX calls time out in 10 second and I also want that all errors should be taken care of in one function. So I called .ajaxSetup method at load time to set up the behavior.


$(function() {
$.ajaxSetup({
 timeout : 10000,
 error: errorDisplay,
 sync: true
});
elClockDisplay = $('#clockDisplay');
elLatencyDisplay = $('#latencyDisplay');
elUpdatesPanel = $('#siteUpdatesPanel');
getServerTime();
}); 

There are lot of other properties that you can set in this structure. I will recommend reading jQuery for latest information about these properties. I will list some of the common ones that you may run into.

  • type
  • beforeSend
  • timeout
  • processData
  • dataTyoe

Views: 3425

Tags: , ,

AJAX | JavaScript | JQuery

How to set cache control headers for AJAX request response

by Admin 22. July 2009 03:03

I have been developing AJAX enabled applications before the term AJAX was coined. I have been doing it for so long that some of things that I do come kind of naturally. And one of the things that I always do is to make sure that response is not cached to ensure that client is never working on stale response even though it sent new request every few seconds. So I have a small piece of code that I pretty much use in all applications that sets some headers.


Response.ContentType = "text/plain";
Response.Expires = -1;
Response.CacheControl = "no-cache";

These are not just the only headers but gives you an idea how cache was being control. I never ran into any trouble with any applications till last week when I was told that our application is filling up Temporary Internet Files folder of the users. This was the first time ever I was reported such issue and actually this was first time I observed this behavior in my applications. So I fired up Fiddler to see whats going on with my requests. I looked at the response headers and saw the following.

First, I was not expecting to see Cache-Control: private. So that was little out of whack. Second, the expiration time was correct because I always set to an hour behind the response time to make sure that it is stale for caching. I have been using the same caching utility routine for so long that I did not suspect that something is wrong there. Then I looked inside Temporary Internet Files folder again and noticed that this was the only request that was being saved in the folder, others were not. So I looked at the implementation and found that the server side implementation for this request was not using my standard utility to set cache headers. Following is the code snippet that I ad in place. Well why i changed the implementation for this particular call is whole different story.


Response.ContentType = "text/plain";
Response.Expires = -1;

Notice that it is missing Cache-control : no-cache header. That explained everything. After I added this header, everything went back to normal. So I decided to do some experiment to observe behavior of setting different headers.

No Cache-control: no-cache header on any call

You will notice that from my earlier post How to serialize multiple AJAX calls in jQuery, I have two AJAX calls being made. And you can see from snapshot above that both are being saved in Temporary Internet File folder.

Cache-control: no-cache header set on one request only

Now you can see that only one request is being saved in the folder and other has disappeared.

Cache-Control:no-cache header set on all requests

Well, there is nothing to show here in Temporary Internet Files folder because nothing is being saved there any more. But here is the snapshot of response headers as seen in Fiddler.

Now you can see that no-cache header and pragma has been set correctly.

Set cache-control header correctly

As more and more applications are using AJAX or Web2.0 style of implementations, if you do not set these cache control headers correctly, you will see that browser cache folders will accumulate lot of entries. It is not that big of a deal as far as application working goes because this temporary cache will not grow beyond specified limits for a particular browser. But it will hurt performance of other internet sites that you visit because their content will not be found in cache and will have to reloaded from server again. Other performance hit you will take is that now browser has to spend an extra CPU cycle to save these entries on the disk.

Views: 2225

Tags: , , , , ,

AJAX | ASP.Net | JavaScript | JQuery

How to serialize multiple jQuery AJAX requests?

by Admin 21. July 2009 11:32

Download Sample Project

In last post, Using jQuery to send AJAX requests, i discussed some basic concepts about how you can use simple .getJSON function to send AJAX requests using jQuery. For discussion of this post, I have added one more AJAX request into the mix. Now I want to another AJAX request to different target. But I want to make sure that second requests is only sent after first one is complete.

There is an async option that you can in jQuery. You can set this option to false to turn your AJAX request into a synchronous request. What this means is that your request is waiting till it completes. If you use this option you can write some code like below.


$(function(){
.getJSON("url1", "", callback1);
.getJSON("url2", "", callback2);
});

There are few issues with this approach. First, your first request will wait till timeout if there is any issue in network. So now your page is waiting as well to render. Second if your second request depends on completion or success of first one, then you do not have control. Second request will be sent no matter what. So setting async flag in general is not something you want to do. More elegent and very simple solution is to make second request in callback function of first request. This way your two calls are serialized now and you still enjoy benefits of async requests. In the sample project for clock synchronization, I have the following code snippet that demonstrates this method of ensuring that second request does not get fired before first one finishes.


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

function getSiteUpdates() {
 cTime = firstRequest ? -1 : curTime.getTime();
 $.getJSON(siteUpdatesServiceUrl, { clientTime: cTime, requestKey: respKey }, gotSiteUpdates);
}

function gotSiteUpdates(data) {
if (data.MessageCount > 0) {
 elUpdatesPanel.append('

' + data.MessageCount + ' updates ' + '

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

Views: 2721

Tags: , , , , ,

AJAX | JQuery

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: 4057

Tags: , ,

ASP.Net | JQuery | AJAX