Ask a Jedi: CFWINDOW for Messaging?

Anjorin asks:

Please am trying do something and i can get the logic. i am working on small site that include an instant messaging section like the one on facebook. i am trying to use cfwindow, but the problem am having is how to have a listener that listens for new messages. Is it possible to have cfwindow call a function recurrently.

Well first off - using something like Flex and LiveCycle Data Services would make this issue trivial. I assume you can’t go that route though. If you want to use a 100% pure Ajax solution, and you want to stick with CF8 (and not use jQuery), then you can do this with polling.

By that I mean you need to have the client perform a request to the server every N seconds or so. This is done pretty easily with the setInterval function. Consider the following:

<html>

<head> <script> function pinger() { ColdFusion.navigate(‘pinger.cfm’,’mydiv’); } </script> </head>

<body onLoad=”setInterval(pinger,4000)”>

<h2>Hello World</h2>

<cfdiv id=”mydiv” /> </body> </html> </code>

I’ve set up the client to run a function, pinger, every 4 seconds. You probably want to make that 30 or even 60. The file you hit, in my case, pinger.cfm, would be responsible for checking to see if a message exists for the user. Here is some simple code I used:

<cfif randRange(1,10) lt 5> <script> ColdFusion.Window.create('win#ranrange(1,999)#','Message','message.cfm?m=x',{center:true,closable:true}); </script> </cfif>

It basically says: If a random number from 1 to 10 is less than 5, make a new window. I named the window dynamically, but you should use another method to give it a truly unique name. I then point it to message.cfm. This is the file that will load the message for the user. The code I used was just this:

<cfparam name="url.m"> <cfoutput>Message #url.m#</cfoutput>

In a real example this would use the database (Transfer FTW) to grab the relevant message, do security checks, etc.

Note that in order for this to work now, back in my first file I have to add:

<cfajaximport tags="cfwindow">

This simply warns ColdFusion to load what it needs for CFWINDOW support.

Any way, the general idea is to run an interval on the client that will poll the server for new messages. Just remember to be gentle with that duration, and I’ll say it again - Flex+LDS allows for real communication and would be your best bet.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments