|
JQuery AJAX Http polling example |
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).
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>
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.
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/.
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!
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.
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.
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.
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.
Great post...did you ever figure out a way to expire/abort the polling?
Thanks!
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?