AJAX Chat Tutorial

6
11/12/11 AJAX Chat Tutorial 1/6 ZZZ.aja[projects.com/aja[/tutorialdetails.php?itemid=9 Home Top Projects Tutorials Articles Submit Project .NET Frameworks Java Frameworks PHP Frameworks Ruby Frameworks Other Frameworks Cool AJAX sites Ajax Resources Ajax Tools JavaScript frameworks MessengerFX ebuddy MSN Web Messenger e-messenger ILoveIM AJAX file upload You Tube KoolIM.com Meebo Ajax.NET Professional Home » Tutorials » AJAX Chat Tutorial AJAX Chat Tutorial AXWhoU: R\DQ SPLWK DRZQORDG VRXUFH FRGH - 7 KE InWUodXcWion TKLV WXWRULDO ZLOO ZDON \RX WKURXJK WKH VWHS LQ RUGHU WR FUHDWH DQ AJAX GULYHQ ZHE FKDW SURJUDP. TKLV ZLOO EH D YHU\ VLPSOH SURJUDP, EXW ZLOO EH H[SDQGHG XSRQ LQ IXWXUH WXWRULDOV. CUeaWing Whe ChaW TableV WH DUH JRLQJ WR FUHDWH WZR WDEOHV IRU WKH FKDW SURJUDP, EXW ZH ZLOO RQO\ XVH RQH IRU WKH ILUVW SDUW RI WKLV WXWRULDO. TKH WZR WDEOHV DUH "FKDW" ZKHUH ZH ZLOO LQ ODWHU WXWRULDOV VWRUH DOO RI WKH GLIIHUHQW FKDW URRPV, DQG "PHVVDJH" ZKLFK FRQWDLQV WKH OLVW RI DOO PHVVDJHV VHQW WR WKH FKDW V\VWHP. --ChaW Table DROP TABLE IF EXISTS `chaW`; CREATE TABLE `chaW` ( `chaW_id` INT(11) NOT NULL AUTO_INCREMENT, `chaW_name` VARCHAR(64) DEFAULT NULL, `VWaUW_Wime` DATETIME DEFA ULT NULL, PRIMARY KEY (`chaW_id`) ) ENGINE=INNODB DEFAULT CHARSET=laWin1; --MeVVage Table DROP TABLE IF EXISTS `meVVage`; CREATE TABLE `meVVage` ( `meVVage_id` INT(11) NOT NULL AUTO_INCREMENT, `chaW_id` INT(11) NOT NULL DEFAULT '0', `XVeU_id` INT(11) NOT N ULL DEFAULT '0', `XVeU_name` VARCHAR(64) DEFAULT NULL, `meVVage` TEXT, `poVW_Wime` DATETIME DEFAULT NULL, PRIMARY KEY (`meVVage_id`) ) ENGINE=INNODB DEFAULT CHARSET=laWin1; TKHVH WDEOHV DUH MXVW D SUHOHPLQDU\ VHWXS DQG ZLOO SUREDEO\ FKDQJH TXLWH D ELW WKURXJK WKHQ XSFRPLQJ SDUWV RI WKHVH WXWRULDOV. TKH HTML SNHOHWRQ TKH HTML LV JRLQJ WR EH SUHWW\ VWUDLJKW IRUZDUG WR VWDUW RXW ZLWK. LHWV VWDUW ZLWK RXU KHDGHU. WH NQRZ WKDW ZH ZLOO ZDQW WR DGG VRPH VW\OH LQIRUPDWLRQ, DQG LQVWHDG RI SODFLQJ LW LQ D VHSHUDWH ILOH, ZH ZLOO OHDYH LW LQ D VFULSW WDJ IRU QRZ LDWHU ZH ZLOO Z DQW WR PRYH WKLV WR DQ H[WHUQDO ILOH IRU FDFKLQJ EHQLILWV, EXW ZH FDQ OHDYH LW KHUH IRU GHYHORSPHQW SXUSRVHV. WH ZLOO DOVR QHHG VRPH JDYDSFUL SW. OQFH DJDLQ ZH FRXOG PRYH WKLV WR DQ H[WHUQDO ILOH, EXW ZH'OO OHDYH LW KHUH IRU QRZ. <hWml> <head> <VW\le W\pe=We[W/cVV media=VcUeen></STYLE> <VcUipW langXage=JaYaScUipW W\pe=We[W/jaYaVcUipW></VcUipW> NoZ leWV add Whe UeVW of Whe HTML: AJAX DUiYen Web Cha W. SWaWXV: NoUmal CXUUenW ChiWWeU-ChaWWeU: <foUm id=fUmmain name=fUmmain onVXbmiW=""> <inpXW id=bWn_geW_chaW W\pe=bXWWon YalXe="RefUeVh ChaW" name=bWn_geW_chaW> <inpXW id=bWn_UeVeW_chaW W\pe=bXWWon YalXe="ReVeW ChaW" name=bWn_UeVeW_chaW> <inpXW id=W[W_meVVage VW\le=" WIDTH: 447p[" name= W[W_meVVage> <inpXW id=bWn_Vend_chaW W\pe=bXWWon YalXe=Send name=bWn_Vend_chaW> </foUm> WH KDYH D KHDGHU, D SDUDJUDSK ZKHUH ZH FDQ GLVSOD\ VWDWXV, D PDLQ GLY WR EH XVHG IRU GLVSOD\LQJ WKH FKDW. AV IRU HTML FRQWUROV, ZH KDYH D UHIUHVK EXWWRQ IRU WHVWLQJ DQG LQFDVH WKH SURJUDP IUHH]HV IRU VRPH UHDVRQ, D UHVHW EXWWRQ WR FOHDU RXW RXU GDWDEDVH, DQ DUHD IRU WKH XVHU WR HQWHU D PHVVDJH, DQG D VHQG EXWWRQ. NRWLFH WKDW ZH KDYH RQH CSS FODVV WKDW ZH KDYHQ'W GHILQHG \HW, DQG RQH LQOLQH CSS VW\OH. WH'OO GHILQH RXU FKDW_PDLQ QH[W. OXU RQH CSS FODVV WKDW ZH KDYH IRU QRZ ZLOO EH. oYeUfloZ: aXWo; heighW: 300p[; Find Aja[ Homes for Sale BUoZVe OXU LiVWingV of HomeV foU Sale in Aja[ OnWaUio. SearchHousesOnline.com « Embed Blogger SlideshoZ CUeaWe SWXnning TUaYel SlideVhoZ In A MinXWe. IWV FUee & EaV\ To ShaUe! tripwow.tripadvisor.com/sl « Chat dengan Pria Asing PUia AVing MencaUi Wani Wa IndoneVia ChaW dan Kencan. IkXW gUaWiV 100%! www.IndonesianCupid.com Drop-DoZn Menus Create cross-browser & feature-rich menus-No programming skills needed! www.likno.com

Transcript of AJAX Chat Tutorial

Page 1: AJAX Chat Tutorial

11/12/11 AJAX Chat Tutorial

1/6www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9

Home Top Projects Tutorials Articles Submit Project

.NET Frameworks

Java Frameworks

PHP Frameworks

Ruby Frameworks

Other Frameworks

Cool AJAX sites

Ajax Resources

Ajax Tools

JavaScript frameworks

MessengerFX

ebuddy

MSN Web Messenger

e-messenger

ILoveIM

AJAX file upload

You Tube

KoolIM.com

Meebo

Ajax.NET Professional

Home » Tutorials » AJAX Chat Tutorial

AJAX Chat Tutorial

Author: Ryan Smith

Download source code - 7 Kb

Introduction

This tutorial will walk you through the step in order to create an AJAX driven web chat program. This will be a very simple program, but

will be expanded upon in future tutorials.

Creating the Chat Tables

We are going to create two tables for the chat program, but we will only use one for the first part of this tutorial. The two tables are

"chat" where we will in later tutorials store all of the different chat rooms, and "message" which contains the list of all messages sent to

the chat system.

- - C h a t T a b l e

D R O P T A B L E I F E X I S T S ` c h a t ` ;

C R E A T E T A B L E ` c h a t ` (

` c h a t _ i d ` I N T ( 1 1 ) N O T N U L L A U T O _ I N C R E M E N T ,

` c h a t _ n a m e ` V A R C H A R ( 6 4 ) D E F A U L T N U L L ,

` s t a r t _ t i m e ` D A T E T I M E D E F A U L T N U L L ,

P R I M A R Y K E Y ( ` c h a t _ i d ` )

) E N G I N E = I N N O D B D E F A U L T C H A R S E T = l a t i n 1 ;

- - M e s s a g e T a b l e

D R O P T A B L E I F E X I S T S ` m e s s a g e ` ;

C R E A T E T A B L E ` m e s s a g e ` (

` m e s s a g e _ i d ` I N T ( 1 1 ) N O T N U L L A U T O _ I N C R E M E N T ,

` c h a t _ i d ` I N T ( 1 1 ) N O T N U L L D E F A U L T ' 0 ' ,

` u s e r _ i d ` I N T ( 1 1 ) N O T N U L L D E F A U L T ' 0 ' ,

` u s e r _ n a m e ` V A R C H A R ( 6 4 ) D E F A U L T N U L L ,

` m e s s a g e ` T E X T ,

` p o s t _ t i m e ` D A T E T I M E D E F A U L T N U L L ,

P R I M A R Y K E Y ( ` m e s s a g e _ i d ` )

) E N G I N E = I N N O D B D E F A U L T C H A R S E T = l a t i n 1 ;

These tables are just a preleminary setup and will probably change quite a bit through then upcoming parts of these tutorials. The

HTML Skeleton The HTML is going to be pretty straight forward to start out with. Lets start with our header. We know that we will

want to add some style information, and instead of placing it in a seperate file, we will leave it in a script tag for now Later we will want

to move this to an external file for caching benifits, but we can leave it here for development purposes. We will also need some

JavaScript. Once again we could move this to an external file, but we'll leave it here for now.

< h t m l >

< h e a d >

< s t y l e t y p e = t e x t / c s s m e d i a = s c r e e n > < / S T Y L E >

< s c r i p t l a n g u a g e = J a v a S c r i p t t y p e = t e x t / j a v a s c r i p t > < / s c r i p t >

N o w l e t s a d d t h e r e s t o f t h e H T M L :

A J A X D r i v e n W e b C h a t .

S t a t u s : N o r m a l

C u r r e n t C h i t t e r - C h a t t e r :

< f o r m i d = f r m m a i n n a m e = f r m m a i n o n s u b m i t = " " >

< i n p u t i d = b t n _ g e t _ c h a t t y p e = b u t t o n v a l u e = " R e f r e s h C h a t " n a m e = b t n _ g e t _ c h a t >

< i n p u t i d = b t n _ r e s e t _ c h a t t y p e = b u t t o n v a l u e = " R e s e t C h a t " n a m e = b t n _ r e s e t _ c h a t >

< i n p u t i d = t x t _ m e s s a g e s t y l e = " W I D T H : 4 4 7 p x " n a m e = t x t _ m e s s a g e >

< i n p u t i d = b t n _ s e n d _ c h a t t y p e = b u t t o n v a l u e = S e n d n a m e = b t n _ s e n d _ c h a t >

< / f o r m >

We have a header, a paragraph where we can display status, a main div to be used for displaying the chat. As for HTML controls, we

have a refresh button for testing and incase the program freezes for some reason, a reset button to clear out our database, an area for

the user to enter a message, and a send button. Notice that we have one CSS class that we haven't defined yet, and one inline CSS

style. We'll define our chat_main next. Our one CSS class that we have for now will be.

o v e r f l o w : a u t o ;

h e i g h t : 3 0 0 p x ;

Find Ajax Homesfor SaleBrowse Our Listings ofHomes for Sale in AjaxOntario.SearchHousesOnline.com…

Embed BloggerSlideshowCreate StunningTravel Slideshow In AMinute. Its Free &Easy To Share!tripwow.tripadvisor.com/sl…

Chat dengan PriaAsingPria Asing MencariWanita Indonesia Chatdan Kencan. Ikutgratis 100%!www.IndonesianCupid.com

Drop-Down MenusCreate cross-browser & feature-richmenus-No programming skills needed!www.likno.com

Page 2: AJAX Chat Tutorial

11/12/11 AJAX Chat Tutorial

2/6www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9

Ajax search in Rails

Jquery Polling

Ajax Tutorial

How To Creating Horizontal CSS

Menu

RSS Ticker with AJAX

ASP.NET AJAX Library Beta in

Visual Studio

File Upload using PHP, Javascript

& Iframe

Saving Session Across Page

Loads Without Cookies, On The

Client Side

Ajax Autosuggest

Developing Ajax Portlets with

Eclipse WTP

h e i g h t : 3 0 0 p x ;

w i d t h : 5 0 0 p x ;

b a c k g r o u n d - c o l o r : # C C C C C C ;

b o r d e r : 1 p x s o l i d # 5 5 5 5 5 5 ;

The only real item of interest here is the overflow. This will allow our div tag to behave like an IFrame. As we will see, this will work very

well for FireFox, but will require some extra code for IE to behave correctly. It is better to use div's with overflows rather than IFrames

because search engines can index them easier.

The Javascript

Let's start with my favorite piece of AJAX code.

/ / G e t s t h e b r o w s e r s p e c i f i c X m l H t t p R e q u e s t O b j e c t

f u n c t i o n g e t X m l H t t p R e q u e s t O b j e c t ( ) {

i f ( w i n d o w . X M L H t t p R e q u e s t ) {

r e t u r n n e w X M L H t t p R e q u e s t ( ) ;

} e l s e i f ( w i n d o w . A c t i v e X O b j e c t ) {

r e t u r n n e w A c t i v e X O b j e c t ( " M i c r o s o f t . X M L H T T P " ) ;

} e l s e {

d o c u m e n t . g e t E l e m e n t B y I d ( ' p _ s t a t u s ' ) . i n n e r H T M L ' S t a t u s : C o u n d n o t c r e a t e X m l H t t p R e q u e s t O b j e c t . ' +

' C o n s i d e r u p g r a d i n g y o u r b r o w s e r . ' ;

}

}

This code creates the XMLHttpRequest object for the current uses values. You will see this code written in many different ways in all

the different AJAX sites out there. A lot of people like to use Try...Catch blocks to check browser compatibility, but I personally think

this way looks more professional. I'm not sure what the best way is, but I've been taught that using Try..Catch blocks leads to sloppy

programming (Damn CS purists.). As you can see, IE suports an ActiveX XMLHttpRequest object, while FireFox, Opera, and the rest use

a native object. If the browser doesn't suport either of these items, we alert the user with our status paragraph. Now we can use this

block of code anywhere we need to create a browser specific XMLHttpRequest object. Lets create 4 global variables. We'll add these to

the top of the script.

v a r s e n d R e q = g e t X m l H t t p R e q u e s t O b j e c t ( ) ;

v a r r e c e i v e R e q = g e t X m l H t t p R e q u e s t O b j e c t ( ) ;

v a r l a s t M e s s a g e = 0 ;

v a r m T i m e r ;

We create two XMLHttpRequest objects, one integer that holds the most recent message that we have recieved (so we don't have to

send the whole message list on each request), and a variable that will store our auto refresh time (so we can clear out our setTimout in

any function). Lets add the function to make the call to get the most recent messages. You can recieve your messages in plain text or

XML. Both have their advantages and disadvantages. For this AJAX app we will be using XML.

/ / G e t s t h e c u r r e n t m e s s a g e s f r o m t h e s e r v e r

f u n c t i o n g e t C h a t T e x t ( ) {

i f ( r e c e i v e R e q . r e a d y S t a t e = = 4 | | r e c e i v e R e q . r e a d y S t a t e = = 0 ) {

r e c e i v e R e q . o p e n ( " G E T " , ' g e t C h a t . p h p ? c h a t = 1 & l a s t = ' + l a s t M e s s a g e , t r u e ) ;

r e c e i v e R e q . o n r e a d y s t a t e c h a n g e = h a n d l e R e c e i v e C h a t ;

r e c e i v e R e q . s e n d ( n u l l ) ;

}

}

First we check to make sure that our XMLHttpRequest object is ready to send a request. We should probably add some code here to

handle other states, but that is too involved for this section. The first line: receiveReq.open("GET", 'getChat.php?chat=1&last=' +

lastMessage, true);Starts the connection to our chat service which will be located at getChat.php along with some data passed as a

querystring. The request type will be a GET. We could also make the request with a POST as you will see in a minute. The second like:

receiveReq.onreadystatechange = handleReceiveChat; sets what JavaScript function will handle the response from the chat service. We

will create this function in a minute. Inside this function we will be able to access the data sent back from the server. The third line

sends the request. Here we pass null because we are doing a GET requets type. If we were using a POST request, we could pass our

parameters here. Now let's create the function tha will handle the servers response:

/ / F u n c t i o n f o r h a n d l i n g t h e r e t u r n o f c h a t t e x t

f u n c t i o n h a n d l e R e c e i v e C h a t ( ) {

i f ( r e c e i v e R e q . r e a d y S t a t e = = 4 ) {

v a r c h a t _ d i v = d o c u m e n t . g e t E l e m e n t B y I d ( ' d i v _ c h a t ' ) ;

v a r x m l d o c = r e c e i v e R e q . r e s p o n s e X M L ;

v a r m e s s a g e _ n o d e s = x m l d o c . g e t E l e m e n t s B y T a g N a m e ( " m e s s a g e " ) ;

v a r n _ m e s s a g e s = m e s s a g e _ n o d e s . l e n g t h

f o r ( i = 0 ; i < n _ m e s s a g e s ; i + + ) {

v a r u s e r _ n o d e = m e s s a g e _ n o d e s [ i ] . g e t E l e m e n t s B y T a g N a m e ( " u s e r " ) ;

v a r t e x t _ n o d e = m e s s a g e _ n o d e s [ i ] . g e t E l e m e n t s B y T a g N a m e ( " t e x t " ) ;

v a r t i m e _ n o d e = m e s s a g e _ n o d e s [ i ] . g e t E l e m e n t s B y T a g N a m e ( " t i m e " ) ;

c h a t _ d i v . i n n e r H T M L + = u s e r _ n o d e [ 0 ] . f i r s t C h i l d . n o d e V a l u e + ' ' ;

c h a t _ d i v . i n n e r H T M L + = ' '

c h a t _ d i v . i n n e r H T M L + = t i m e _ n o d e [ 0 ] . f i r s t C h i l d . n o d e V a l u e + '

' ;

c h a t _ d i v . i n n e r H T M L + = t e x t _ n o d e [ 0 ] . f i r s t C h i l d . n o d e V a l u e + '

' ;

l a s t M e s s a g e = ( m e s s a g e _ n o d e s [ i ] . g e t A t t r i b u t e ( ' i d ' ) ) ;

}

m T i m e r = s e t T i m e o u t ( ' g e t C h a t T e x t ( ) ; ' , 2 0 0 0 ) ;

Page 3: AJAX Chat Tutorial

11/12/11 AJAX Chat Tutorial

3/6www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9

m T i m e r = s e t T i m e o u t ( ' g e t C h a t T e x t ( ) ; ' , 2 0 0 0 ) ;

}

There is a lot of stuff going on in this function so let's just take it one line at a time. The first line:

i f ( r e c e i v e R e q . r e a d y S t a t e = = 4 ) {

Check to see if the response from the server was good. We could do error handling here if we would like. The next line is just setting

up a short-cut variable for later use. The third line creates the XMLDoc object that contains the servers response information.

v a r x m l d o c = r e c e i v e R e q . r e s p o n s e X M L ;

We could also get this data as plain text with receiveReq.response.Text. Plain text is better when you are returning a single value, but

XML is easier for multiple values. Since we will be returning multiple messages with 4 values each on every request, XML is the way to

go. In order to work with XML responses, you need to understand the XMLDOM. There can be some tricky litt le differences between

the browsers when working with the XMLDOM. The next line:

v a r m e s s a g e _ n o d e s = x m l d o c . g e t E l e m e n t s B y T a g N a m e ( " m e s s a g e " ) ;

Get's all the messages for this request. Each message node contains multiple pieces of information about the message. Below is an

example of how our response XML will look:

< R O O T >

< M E S S A G E i d ϝ>

< U S E R > R y a n S m i t h < / U S E R >

< T E X T > H e r e i s t h e M e s s a g e T e x t < / T E X T >

< T I M E > 0 7 : 5 3 < / T I M E >

< / M E S S A G E >

< / R O O T >

We can have multiple message elements in each response. We pass along the Users Name who posted the message, the message text,

and the current time that the message was posted. The next two lines start the loop through the messages from the response.

v a r n _ m e s s a g e s = m e s s a g e _ n o d e s . l e n g t h

f o r ( i = 0 ; i < n _ m e s s a g e s ; i + + ) { F o r e v e r y m e s s a g e w e w i l l a l l t h e n e w m e s s a g e t o o u r c h a t s c r e e n .

v a r u s e r _ n o d e = m e s s a g e _ n o d e s [ i ] . g e t E l e m e n t s B y T a g N a m e ( " u s e r " ) ;

v a r t e x t _ n o d e = m e s s a g e _ n o d e s [ i ] . g e t E l e m e n t s B y T a g N a m e ( " t e x t " ) ;

v a r t i m e _ n o d e = m e s s a g e _ n o d e s [ i ] . g e t E l e m e n t s B y T a g N a m e ( " t i m e " ) ;

c h a t _ d i v . i n n e r H T M L + = u s e r _ n o d e [ 0 ] . f i r s t C h i l d . n o d e V a l u e + ' ' ;

c h a t _ d i v . i n n e r H T M L + = ' '

c h a t _ d i v . i n n e r H T M L + = t i m e _ n o d e [ 0 ] . f i r s t C h i l d . n o d e V a l u e + '

' ;

c h a t _ d i v . i n n e r H T M L + = t e x t _ n o d e [ 0 ] . f i r s t C h i l d . n o d e V a l u e + '

' ;

The next six lines just update our chat display from the results of the server. Finally we store the last ID that we recieved from the

server so that we can avoid receiving duplicate data.

l a s t M e s s a g e = ( m e s s a g e _ n o d e s [ i ] . g e t A t t r i b u t e ( ' i d ' ) ) ;

A f t e r w e h a v e u p d a t e d o u r d i s p l a y , w e w i l l s e t a t i m e o u t t o r e f r e s h o u r d i s p l a y .

m T i m e r = s e t T i m e o u t ( ' g e t C h a t T e x t ( ) ; ' , 2 0 0 0 ) ;

We will send another request to the server in 2 seconds to see if any new messages have been posted. We also store it in our global

variable so that we can clear it out later. Sending the Request We need to write the code to send a message to the server. When

sending our message, we will use a POST request rather than a GET. This allows us to send larger messages to the server because the

overall size of a querystring is limited. Creating a POST request is a lot like creating a GET request.

/ / A d d a m e s s a g e t o t h e c h a t s e r v e r .

f u n c t i o n s e n d C h a t T e x t ( ) {

i f ( s e n d R e q . r e a d y S t a t e = = 4 | | s e n d R e q . r e a d y S t a t e = = 0 ) {

s e n d R e q . o p e n ( " P O S T " , ' g e t C h a t . p h p ? c h a t = 1 & l a s t = ' + l a s t M e s s a g e , t r u e ) ;

s e n d R e q . s e t R e q u e s t H e a d e r ( ' C o n t e n t - T y p e ' , ' a p p l i c a t i o n / x - w w w - f o r m - u r l e n c o d e d ' ) ;

s e n d R e q . o n r e a d y s t a t e c h a n g e = h a n d l e S e n d C h a t ;

v a r p a r a m = ' m e s s a g e = ' + d o c u m e n t . g e t E l e m e n t B y I d ( ' t x t _ m e s s a g e ' ) . v a l u e ;

p a r a m + = ' & n a m e = R y a n S m i t h ' ;

p a r a m + = ' & c h a t = 1 ' ;

s e n d R e q . s e n d ( p a r a m ) ;

d o c u m e n t . g e t E l e m e n t B y I d ( ' t x t _ m e s s a g e ' ) . v a l u e = ' ' ;

}

} A s y o u c a n s e e , i t ' s p r e t t y m u c h t h e s a m e c o d e , b u t w h e n w e c a l l t h e s e n d ( ) m e t h o d , w e p a s s i n a n a d d i t i o n a l p a r a m e t e r .

v a r p a r a m = ' m e s s a g e = ' + d o c u m e n t . g e t E l e m e n t B y I d ( ' t x t _ m e s s a g e ' ) . v a l u e ;

p a r a m + = ' & n a m e = R y a n S m i t h ' ;

p a r a m + = ' & c h a t = 1 ' ;

s e n d R e q . s e n d ( p a r a m ) ;

We are passing three values in our POST data; the message text, the user's name(HardCoded to my name right now, and the current

chat room (HardCoded to 1 right now). We'll change these later to allow for different chat rooms and different user names. On this

request, instead of executing handleReceiveChat on the callback, we will execute a new function called handleSendChat. This function

is going to be pretty simple.

/ / W h e n o u r m e s s a g e h a s b e e n s e n t , u p d a t e o u r p a g e .

f u n c t i o n h a n d l e S e n d C h a t ( ) {

/ / C l e a r o u t t h e e x i s t i n g t i m e r s o w e d o n ' t h a v e

/ / m u l t i p l e t i m e r i n s t a n c e s r u n n i n g .

c l e a r I n t e r v a l ( m T i m e r ) ;

g e t C h a t T e x t ( ) ;

}

Page 4: AJAX Chat Tutorial

11/12/11 AJAX Chat Tutorial

4/6www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9

}

All we are doing here is clearing out any refresh timer that may be executing, and then making the call to refresh the chat. This sets up

our client side functionality for sending and receiving chat messages. The one last piece of functionality that we want to add right now

is the ability to reset our chat application.

/ / T h i s c l e a n s o u t t h e d a t a b a s e s o w e c a n s t a r t a n e w c h a t s e s s i o n .

f u n c t i o n r e s e t C h a t ( ) {

i f ( s e n d R e q . r e a d y S t a t e = = 4 | | s e n d R e q . r e a d y S t a t e = = 0 ) {

s e n d R e q . o p e n ( " P O S T " , ' c h a t / g e t C h a t . p h p ? c h a t = 1 & l a s t = ' + l a s t M e s s a g e , t r u e ) ;

s e n d R e q . s e t R e q u e s t H e a d e r ( ' C o n t e n t - T y p e ' , ' a p p l i c a t i o n / x - w w w - f o r m - u r l e n c o d e d ' ) ;

s e n d R e q . o n r e a d y s t a t e c h a n g e = h a n d l e R e s e t C h a t ;

v a r p a r a m = ' a c t i o n = r e s e t ' ;

s e n d R e q . s e n d ( p a r a m ) ;

d o c u m e n t . g e t E l e m e n t B y I d ( ' t x t _ m e s s a g e ' ) . v a l u e = ' ' ;

}

}

We create a function that is pretty much the same as our sendChatText function, but instead of passing a message in the POST

parameters, we will pass an "action" parameter with the value of reset. Our callback for the resetChat request simply clears out any

messages that are currently in the chat display and resets our refresh timer.

/ / T h i s f u n c t i o n h a n d l e s t h e r e s p o n s e a f t e r t h e p a g e h a s b e e n r e f r e s h e d .

f u n c t i o n h a n d l e R e s e t C h a t ( ) {

d o c u m e n t . g e t E l e m e n t B y I d ( ' d i v _ c h a t ' ) . i n n e r H T M L = ' ' ;

c l e a r I n t e r v a l ( m T i m e r ) ;

g e t C h a t T e x t ( ) ;

}

We'll finish off our JavaScript by adding our onclick handlers to our buttons.

< i n p u t i d = b t n _ g e t _ c h a t o n c l i c k = j a v a s c r i p t : g e t C h a t T e x t ( ) ;

t y p e = b u t t o n v a l u e = " R e f r e s h C h a t " n a m e = b t n _ g e t _ c h a t >

< i n p u t i d = b t n _ r e s e t _ c h a t o n c l i c k = j a v a s c r i p t : r e s e t C h a t ( ) ;

t y p e = b u t t o n v a l u e = " R e s e t C h a t " n a m e = b t n _ r e s e t _ c h a t >

< i n p u t i d = t x t _ m e s s a g e s t y l e = " W I D T H : 4 4 7 p x " n a m e = t x t _ m e s s a g e >

< i n p u t i d = b t n _ s e n d _ c h a t o n c l i c k = j a v a s c r i p t : s e n d C h a t T e x t ( ) ;

t y p e = b u t t o n v a l u e = S e n d n a m e = b t n _ s e n d _ c h a t >

F o r e a c h b u t t o n c l i c k , w e c a l l i t ' s c o r r e s p o n d i n g J a v a S c r i p t f u n c t i o n

The Backend

Now it's time to create the back-end to the chat application. The way we have setup our client-side, all requests go to the same URL.

The backend decides how to handle this based on the parameters passed with the request. The first thing that our back-end file does

is create some HTTP headers to keep the clients brower from caching the respose.

/ / S e n d s o m e h e a d e r s t o k e e p t h e u s e r ' s b r o w s e r f r o m c a c h i n g t h e r e s p o n s e .

h e a d e r ( " E x p i r e s : M o n , 2 6 J u l 1 9 9 7 0 5 : 0 0 : 0 0 G M T " ) ;

h e a d e r ( " L a s t - M o d i f i e d : " . g m d a t e ( " D , d M Y H : i : s " ) . " G M T " ) ;

h e a d e r ( " C a c h e - C o n t r o l : n o - c a c h e , m u s t - r e v a l i d a t e " ) ;

h e a d e r ( " P r a g m a : n o - c a c h e " ) ;

h e a d e r ( " C o n t e n t - T y p e : t e x t / x m l ; c h a r s e t = u t f - 8 " ) ;

You can see that we set the "Expires" header to a date that has already passed. Without this line, IE tends to cache the response

regardless of the other headers. The one other header we send is the Content-Type. We set our content type to text/xml so the

clients browser knows that we are sending an XML file rather then a text file. This eases the creation of the XMLDoc object for the

different browser types. The next line includes a file that contains our database functions. I like to abstract my database functions in a

seperate file in case I need to change by database connection type (MSSQL, Oracle, etc.). require('database.php');I'll explain this file in

a litt le bit. The first action that we perform is to check our POST variables to see if a new message was sent in the request.

/ / C h e c k t o s e e i f a m e s s a g e w a s s e n t .

i f ( i s s e t ( $ _ P O S T [ ' m e s s a g e ' ] ) & & $ _ P O S T [ ' m e s s a g e ' ] ! = ' ' ) {

$ s q l = " I N S E R T I N T O m e s s a g e ( c h a t _ i d , u s e r _ i d , u s e r _ n a m e , m e s s a g e , p o s t _ t i m e ) V A L U E S ( " .

d b _ i n p u t ( $ _ G E T [ ' c h a t ' ] ) . " , 1 , ' " . d b _ i n p u t ( $ _ P O S T [ ' n a m e ' ] ) .

" ' , ' " . d b _ i n p u t ( $ _ P O S T [ ' m e s s a g e ' ] ) . " ' , N O W ( ) ) " ;

d b _ q u e r y ( $ s q l ) ;

}

If a new message was sent, then we add the message to our database. $sql is a string containing the query text. We use to the

function db_input to escape any quote characters that the user may have entered. We then execute the query text with our

db_query function. Next we'll check to see if a request to reset the chat was sent:

/ / C h e c k t o s e e i f a r e s e t r e q u e s t w a s s e n t .

i f ( i s s e t ( $ _ P O S T [ ' a c t i o n ' ] ) & & $ _ P O S T [ ' a c t i o n ' ] = = ' r e s e t ' ) {

$ s q l = " D E L E T E F R O M m e s s a g e W H E R E c h a t _ i d = " . d b _ i n p u t ( $ _ G E T [ ' c h a t ' ] ) ;

d b _ q u e r y ( $ s q l ) ;

}

Once again we create our query text and execute it with our db_query function. This query simply deletes all messages from the

database that are from the current chat session. Now it's time to create the response that will get sent back to the use. After we have

finished updating the database with any new messages sent by the user, we will get the list of any new messages that the user hasn't

recieved yet. We start by creating our XML header and document element opening tag.

/ / C r e a t e t h e X M L r e s p o n s e .

$ x m l = ' < ? x m l v e r s i o n = " 1 . 0 " ? > < R O O T > ' ;

Page 5: AJAX Chat Tutorial

11/12/11 AJAX Chat Tutorial

5/6www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9

$ x m l = ' < ? x m l v e r s i o n = " 1 . 0 " ? > < R O O T > ' ;

It is important to note that there cannot be any whitespace or other characters before our XML declaration, otherwise we will run into

processing errors when trying to parse the XMLDom on the client-side. Next, we will check to see if the user is in a chat room. If not

we will send the user a message informing them that they need to enter a chat room before they can get any chat messages.

/ / C h e c k t o e n s u r e t h e u s e r i s i n a c h a t r o o m .

i f ( ! i s s e t ( $ _ G E T [ ' c h a t ' ] ) ) {

$ x m l . = ' Y o u r a r e n o t c u r r e n t l y i n a c h a t s e s s i o n . E n t e r a c h a t s e s s i o n h e r e ' ;

$ x m l . = ' < M E S S A G E i d = 0 > ' ;

$ x m l . = ' < U S E R > A d m i n < / U S E R > ' ;

$ x m l . = ' < T E X T > Y o u r a r e n o t c u r r e n t l y i n a c h a t s e s s i o n . ' ;

$ x m l . = ' < a h r e f = " " > E n t e r a c h a t s e s s i o n h e r e < / a > < / T E X T > ' ;

$ x m l . = ' < T I M E > ' . d a t e ( ' h : i ' ) . ' < / T I M E > ' ;

$ x m l . = ' < / M E S S A G E > ' ;

We have an empty link in this message that we can later replace with a URL to our chat room selection page, but that is beyond the

scope of this tutorial. If the user is in a chat room, then we will get every message that the user hasn't received yet and add them to

our XML response.

} e l s e {

$ l a s t = ( i s s e t ( $ _ G E T [ ' l a s t ' ] ) & & $ _ G E T [ ' l a s t ' ] ! = ' ' ) ? $ _ G E T [ ' l a s t ' ] : 0 ;

$ s q l = " S E L E C T m e s s a g e _ i d , u s e r _ n a m e , m e s s a g e , d a t e _ f o r m a t ( p o s t _ t i m e , ' % h : % i ' ) a s p o s t _ t i m e " .

" F R O M m e s s a g e W H E R E c h a t _ i d = " . d b _ i n p u t ( $ _ G E T [ ' c h a t ' ] ) . " A N D m e s s a g e _ i d > " . $ l a s t ;

$ m e s s a g e _ q u e r y = d b _ q u e r y ( $ s q l ) ;

w h i l e ( $ m e s s a g e _ a r r a y = d b _ f e t c h _ a r r a y ( $ m e s s a g e _ q u e r y ) ) {

$ x m l . = ' < M E S S A G E i d = " ' . $ m e s s a g e _ a r r a y [ ' m e s s a g e _ i d ' ] . ' " > ' ;

$ x m l . = ' < U S E R > ' . h t m l s p e c i a l c h a r s ( $ m e s s a g e _ a r r a y [ ' u s e r _ n a m e ' ] ) . ' < / U S E R > ' ;

$ x m l . = ' < T E X T > ' . h t m l s p e c i a l c h a r s ( $ m e s s a g e _ a r r a y [ ' m e s s a g e ' ] ) . ' < / T E X T > ' ;

$ x m l . = ' < T I M E > ' . $ m e s s a g e _ a r r a y [ ' p o s t _ t i m e ' ] . ' < / T I M E > ' ;

$ x m l . = ' < / M E S S A G E > ' ;

}

}

The first step here is to check and see if the user has recieved any messages yet. If the request didn't specify the last request

recieved, then we set the $last variable to zero in order to get every previous message for this chat session Next, we create our SQL

statement to get all the message for the current chat session that were posted since our last update. By limiting our request to just

the messages that we haven't recieved yet, we reduce the amount of network traffic we need to send as well as limit the client site

work involved. After we have performed our query, we loop through each message row and add a message node to our XML. Each

message node contains the message id, the user who posted the message, the text of the message, and the time the message was

posted. Finally, we close out our XML document element and add our XML to the response.

$ x m l . = ' < / R O O T > ' ;

e c h o $ x m l ;

We are now ready to test out our Chat Function. Be sure that you have created the database tables and set the correct database

connection value in database.php.

www.Ajaxprojects.com For more Ajax tutorials

Usability Additions

We can see that we have a semi-functioning AJAX driven chat application. To finish off part one of this tutorial, we will make a few small

additions to the HTML in order to make it a bit more user friendly. One of the first things you'll probably notice is that when you type a

message and press enter, the page refreshes and your message isn't added. You have to actually click the "Send" button to add your

message to the chat. To fix this, we will add a simple JavaScript function that is called on the form's submit event.

This function will call our sendChatText function and return false to keep the form from submitting. //This functions handles when the

user presses enter. Instead of submitting the form, we //send a new message to the server and return false.

f u n c t i o n b l o c k S u b m i t ( ) {

s e n d C h a t T e x t ( ) ;

r e t u r n f a l s e ;

}

This will add our message to the chat every time we enter a message and press enter. You will also notice that when you first open

the page, the chat is not refreshing itself. We will create a JavaScript function that is called when the page loads to handle initializing

our application.

When the document loads, we start refreshing the chat messages by calling the getChatText() function.

/ / F u n c t i o n f o r i n i t i a l i z a t i n g t h e p a g e .

f u n c t i o n s t a r t C h a t ( ) {

/ / S e t t h e f o c u s t o t h e M e s s a g e B o x .

d o c u m e n t . g e t E l e m e n t B y I d ( ' t x t _ m e s s a g e ' ) . f o c u s ( ) ;

/ / S t a r t R e c i e v i n g M e s s a g e s .

g e t C h a t T e x t ( ) ;

}

Additionaly we set the focus to the message textbox so the user can immediately start typing a message. This concludes the first part

of the AJAX driven web chat tutorial. In the next installment, we will see how to create multiple chat rooms with different user names.

We will also see other ways to extend our chat application to make it more robust and user friendly. Hopefully this tutorial gave you a

good introduction to creating application using AJAX technologies.

www.Ajaxprojects.com For more Ajax tutorials

Page 6: AJAX Chat Tutorial

11/12/11 AJAX Chat Tutorial

6/6www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9

Copyrights Reserved AjaxProjects.com 2006-2010, Developed by IRange -Privacy Policy