Tuesday, January 25, 2011

Basic Polling Web jQuery Chat Example Using WebMatrix

*** Update: I had a bunch of junk comments left over from testing in the sdf database, some were kind of crude. I removed them from the source. Numbers 32:23 in action :) ***

Ok, here is a VERY rudimentary example to help you get web chat functionality going in a webmatrix site. I'm not getting fancy at all here, just three pages and a SQL CE database -> Chatpage.cshtml, pull.cshtml, push.cshtml. Essentially I've got my chat page that uses jQuery to poll a "pull" page every 1.5 seconds. I keep track of what data to return by using session time variables. And there is a simple jQuery post method to post new chat messages.

Note! This is just meant to help get you going, not meant to be production code (no SQL injection defense, might need to watch out for Chars in Javascript that might throw things off, not styled at all, yadda yadda yadda). But there is enough here to get you going. Also be warned that you need to test this with two different types of browsers if you are testing the code on your local machine (else a same browser just different windows will share the same session and messages will start disappearing).

Here is the [Source Code]. Or you can look at each page's source individually (scroll bars at the bottom of the code if it over flows).

Here is the ChatPage.cshtml

Here is the Push.cshtml page source

Here is the Pull.cshtml page source

Here is a picture of the database schema

No comments: