Shaun Mccran

My digital playground

26
S
E
P
2010

JQuery AJAX Http polling example

I've been using the JQuery post() and get() functions for a while now, and thanks to decent Blog entries from other community members I've got my head around the principles of seamless AJAX http requests and response handling.

This article examines a way of creating a polling AJAX http request. This is a request that will run every N seconds based on a value. It will hit a remote service and return a result, and display that result on screen.

View a full demo of an AJAX polling request here.

The remote service CFC

The remote service I am using in this example is a Coldfusion CFC that that returns the date and time. It simply formats the date and time and returns it as a JSON object. You can use the CFJSON CFC or just specify a returnformat value of 'JSON', in the CFC function (depends on your server version).

view plain print about
1<cffunction name="getTime"
2            access="remote"
3            output="true"
4            returntype="void"
5            hint="returns the time to remote calls">

6
7        <cfset var response = "Test">
8        <cfset response = '{"status":"success","data":{"date":"#dateformat(now(), 'dd-mm-yyyy')#","time":"#dateFormat(now(), 'HH:mm:ss')#"}}'>
9
10        <cfoutput>#response#</cfoutput>
11    </cffunction>
Amended

After testing I discovered that the CFC above included extra whitespace that wrecks the JSON response in IE browsers. Instead I am using a cfm template like this.

view plain print about
1<cfsilent>
2<cfsetting showDebugOutput=false>
3<cfsetting enablecfoutputonly="true">
4<cfprocessingdirective suppresswhitespace="true">
5<cfsavecontent variable="response"><cfoutput>{"status":"success","data":{"date":"#dateformat(now(), 'dd-mm-yyyy')#","time":"#dateFormat(now(), 'HH:mm:ss')#"}}</cfoutput></cfsavecontent>
6</cfprocessingdirective>
7</cfsilent>
8<cfoutput>#response#</cfoutput>

JQuery AJAX http polling request

Include the JQuery libraries from Google, and the polling.js plugin. Nick Riggs has taken the JQuery functions of ajax(); get() and post(); and extended them to create a plugin: http://www.nickriggs.com/posts/simple-ajax-polling-plugin-for-jquery/.

view plain print about
1<s/cript type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js"></script>
2<s/cript type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
3<s/cript language="javascript" src="polling.js" type="text/javascript"></script>

The code below is one example of how you can use several of the default values to set the type of polling to 'interval' IE continuous polling at a certain number of seconds. the ajaxPoll() method accepts a series of values specifying the url to request, any data to pass to it and how the response should be handled.

I've wrapped this in a click event to show how you could initialise the polling function. I'd quite like to create a stop event as well, but haven't quite got that working. (Hint)

The example uses the JQuery append() method to display the result in a div. I'm incrementing a counter in this routine as well, the counter is all client side to avoid passing data from client to server that you don't need to. Remember keep it as light as possible!

view plain print about
1<s/cript type="text/javascript">
2    $(document).ready(function(){
3
4    $("#start").click(function(){
5
6        $.ajaxPollSettings.pollingType = "interval";
7        $.ajaxPollSettings.interval = 5000;
8
9        var httpcount = 1;
10
11        $.ajaxPoll({
12         url: "map-service.cfc?method=getTime",
13         type: "POST",
14         data: { count: httpcount},
15         dataType: "json",
16         successCondition: function(result) {
17         // return result != null; // custom condition goes here.
18
19         var responseString = httpcount + '. ' + result.data.date + ' ' + result.data.time + '<br>';
20
21         $("#response-container").append(responseString);
22
23                httpcount = httpcount + 1;
24
25         },
26         success: function(result) {
27         // alert(result.status);
28         // alert(result.data.date);
29         }
30        });
31
32    });
33
34    $("#stop").click(function(){
35
36        alert('will write stop function here');
37
38        });
39
40});
41</script>

This is the div that shows the response, and the start / stop buttons.

view plain print about
1<input type="button" value="start" id="start">
2<input type="button" value="stop" id="stop">
3
4<h2>Ajax responses</h2>
5<div id="response-container"></div>

If you use firebug or Charles (web proxy tracking software) you can watch each request firing. Most of the request return a difference of five seconds, but I see the odd delayed one with a slightly longer time.

View a full demo of an AJAX polling request here.

I built this to use in a Google Map application, to poll map points, so look out for that article next.

Related Blog Entries

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Kamil's Gravatar Works fine on Firefox -- not on IE 8 on XP SP3.
# Posted By Kamil | 26/09/2010 20:07
Shaun McCran's Gravatar Hi,
Yes, you are right, there seems to be an issue in IE. Using Charles I can see that the first request is being made, but the subsequent ones are not. I shall debug and amend.
# Posted By Shaun McCran | 26/09/2010 21:02
Shaun McCran's Gravatar The IE error was in the response from the JSON object. There was extra white space around the returned object.

Writing it like this:

<cfsilent>
<cfsetting showDebugOutput=false>
<cfsetting enablecfoutputonly="true">
<cfprocessingdirective suppresswhitespace="true">
<cfsavecontent variable="response"><cfoutput>{"status":"success","data":{"date":"#dateformat(now(), 'dd-mm-yyyy')#","time":"#dateFormat(now(), 'HH:mm:ss')#"}}</cfoutput></cfsavecontent>
</cfprocessingdirective>
</cfsilent>
<cfoutput>#response#</cfoutput>


Fixes any IE issues.
# Posted By Shaun McCran | 26/09/2010 22:18
Mohamed's Gravatar thanks.
# Posted By Mohamed | 12/12/2011 09:25
Phil Rodopoulos's Gravatar Shaun,

Great post...did you ever figure out a way to expire/abort the polling?

Thanks!
# Posted By Phil Rodopoulos | 24/02/2012 09:50
Shaun McCran's Gravatar Hi Phil,

Thanks, glad you liked it. I haven't re-visited this since writing the original article as I used it in a project and then left it behind. I'll have a look into it as it would be good to do.

Do you have an inspiration as to how to do it then?
# Posted By Shaun McCran | 26/02/2012 12:20
rosaline's Gravatar We too wanna send you a request on how to use this AJAX polling as of now without any drawbacks. We are also waiting for the immediate reply from you. You can ping us at http://www.fastessaywriting.net/ as soon as you get the answer.
# Posted By rosaline | 20/06/2015 04:34
Kevin's Gravatar You have shared an informative thread. I have searched a lot to get the exact details regarding this topic. But I didn’t the proper description. Now I got the right option to execute this function. Thank you very much!
# Posted By Kevin | 30/06/2015 21:45
owning's Gravatar We are having so many educational websites like http://www.dissertationworld.biz/. These are all using to create many educational services and content writing books for our college students.
# Posted By owning | 09/07/2015 00:41
# Posted By Packers And Movers India | 22/09/2015 04:20
mrdavidcaminer's Gravatar I've been using the JQuery post() and get() functions for a while now, and thanks to decent Blog entries from other community members I've got my head around the principles of seamless AJAX http requests and response handling.
# Posted By mrdavidcaminer | 03/10/2015 07:03
Plumbing Service's Gravatar every N seconds based on a value. It will hit a remote service and return a result, and display that result on screen.
# Posted By Plumbing Service | 22/11/2015 00:37
free facebook likes's Gravatar Nice Informative Blog having nice sharing..
# Posted By free facebook likes | 14/12/2015 23:48
free youtube views's Gravatar including reasonable comments here...
# Posted By free youtube views | 14/12/2015 23:50
cccam server's Gravatar I want you to thank for your time of this wonderful read!!! I definitely enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog....
# Posted By cccam server | 18/12/2015 23:48
dedicated server reseller's Gravatar Nick Riggs has taken the JQuery functions of ajax(); get() and post(); and extended them to create a plugin:
# Posted By dedicated server reseller | 19/12/2015 23:09
cccam server's Gravatar I want you to thank for your time of this wonderful read!!! I definitely enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog....
# Posted By cccam server | 22/12/2015 04:13
packers and movers pune to hyderabad's Gravatar this wonderful read!!! I definitely enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog....
# Posted By packers and movers pune to hyderabad | 14/01/2016 01:07
Back to top