AJAX Chat Room - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

AJAX Chat Room

Description:

AJAX Chat Room – PowerPoint PPT presentation

Number of Views:159
Avg rating:3.0/5.0
Slides: 10
Provided by: chrisn
Category:
Tags: ajax | chat | room

less

Transcript and Presenter's Notes

Title: AJAX Chat Room


1
AJAX Chat Room
  • An example from AJAX and PHP
  • As implemented by Chris Newlon
  • Darie, C., Brinzarea, B., Chereches-Tosa, F.,
    Bucica, M. (2006). AJAX and PHP Building
    Responsive Web Applications. Birmingham, U.K.
    Packt Publishing Ltd.

2
Features of the chat room
  • Message window
  • Input box with submit button
  • Color selector
  • Delete button to clear the database
  • Location
  • http//sandbox.informatics.iupui.edu/cnewlon/Coll
    aborationProductionSite/

3
Code files used
  • index.html basic page elements
  • chat.css formatting
  • chat.js AJAX code
  • chat.php receives posts
  • chat.class.php object, handles database
  • (several utilities and the spectrum image)
  • Note SQL was rewritten because server doesnt
    implement mysqli

4
Code from index.html
  • type"text/css" /
  • Your browser does not support JavaScript!!
  • Palette" border"1"
    onclick"getColor(event)"/

  • readonly"true" value"000000" /
  • size"10" onblur"checkUsername()"/
  • maxlength"2000" size"50"
  • onkeydown"handleKey(event)"/
  • onclick"sendMessage()" /
  • onclick"deleteMessages()" /

5
Code from chat.php
  • // reference the file containing the Chat class
  • require_once("chat.class.php")
  • // retrieve the operation to be performed
  • mode _POST'mode'
  • // create a new Chat instance
  • chat new Chat()
  • // if the operation is SendAndRetrieve
  • if(mode 'SendAndRetrieveNew')
  • // retrieve the action parameters used to add a
    new message
  • name _POST'name'
  • message _POST'message'
  • color _POST'color'
  • id _POST'id'
  • // post the message to the database
  • chat-postMessage(name, message, color)
  • // if the operation is DeleteAndRetrieve
  • elseif(mode 'DeleteAndRetrieveNew')
  • // delete all existing messages
  • chat-deleteMessages()
  • // if the operation is Retrieve
  • elseif(mode 'RetrieveNew')
  • // get the id of the last message retrieved by
    the client
  • id _POST'id'
  • // retrieve new messages from the server
  • echo chat-retrieveNewMessages(id)
  • ?

6
Code from chat.class.php
  • / The postMessages method inserts a message
    into the database
  • - name represents the name of the user that
    posted the message
  • - messsage is the posted message
  • - color contains the color chosen by the user
    /
  • public function postMessage(name, message,
    color)
  • // build the SQL query that adds a new
    message to the server
  • query 'INSERT INTO chat2(posted_on,
    user_name, message, color) ' .
  • 'VALUES (NOW(), "' . name . '" , "'
    . message .
  • '","' . color . '")'
  • // execute the SQL query
  • result mysql_query(query,this-accessConn
    )
  • / The retrieveNewMessages method retrieves
    the new messages that have been posted to the
    server. - the id parameter is sent by the
    client and it represents the id of the last
    message received by the client. Messages more
    recent by id will be fetched from the database
    and returned to the client in XML format. /
  • public function retrieveNewMessages(id0)
  • // compose the SQL query that retrieves new
    messages
  • if(id0)
  • // retrieve messages newer than id
  • query 'SELECT chat_id, user_name,
    message, color, ' .
  • ' DATE_FORMAT(posted_on, "Y-m-d
    His") ' .
  • ' AS posted_on ' .
  • ' FROM chat2 WHERE chat_id ' . id .
  • ' ORDER BY chat_id ASC'

7
Code from chat.class.php (cont.)
  • // on the first load only retrieve the last 50
    messages from server
  • query
  • ' SELECT chat_id, user_name, message,
    color, posted_on FROM ' .
  • ' (SELECT chat_id, user_name, message,
    color, ' .
  • ' DATE_FORMAT(posted_on, "Y-m-d
    His") AS posted_on ' .
  • ' FROM chat2 ' .
  • ' ORDER BY chat_id DESC ' .
  • ' LIMIT 50) AS Last50' .
  • ' ORDER BY chat_id ASC'
  • // loop through all the fetched messages to build
    the result message
  • while (rowmysql_fetch_assoc(result))
  • id row'chat_id'
  • color htmlspecialchars
    (row'color')
  • userName htmlspecialchars
    (row'user_name')
  • time htmlspecialchars
    (row'posted_on')
  • message htmlspecialchars
    (row'message')
  • response . '' . id . '' .
  • '. '' .
  • '' . time . ''
    .
  • 'userName . '' .
  • 'message . ''

8
Code from chat.js
  • / creates an XMLHttpRequest instance /
  • function createXmlHttpRequestObject()
  • // will store the reference to the
    XMLHttpRequest object
  • var xmlHttp
  • // this should work for all browsers except IE6
    and older
  • try
  • // try to create XMLHttpRequest object
  • xmlHttp new XMLHttpRequest()
  • catch(e)
  • // assume IE6 or older
  • var XmlHttpVersions new Array("MSXML2.XMLHTT
    P.6.0",
  • "MSXML2.XMLHTTP.5.0",
  • "MSXML2.XMLHTTP.4.0",
  • "MSXML2.XMLHTTP.3.0",
  • "MSXML2.XMLHTTP",
  • "Microsoft.XMLHTTP")
  • // try every prog id until one works
  • for (var i0 i!xmlHttp i)
  • try
  • // try to create XMLHttpRequest object
  • xmlHttp new ActiveXObject(XmlHttpVersion
    si)
  • catch (e)
  • // return the created object or display an
    error message
  • if (!xmlHttp)
  • alert("Error creating the XMLHttpRequest
    object.")
  • else
  • return xmlHttp

9
Code from chat.js (cont.)
  • / function called when the Send button is
    pressed /
  • function sendMessage()
  • // save the message to a local variable and
    clear the text box
  • var oCurrentMessage document.getElementById("m
    essageBox")
  • var currentUser document.getElementById("userN
    ame").value
  • var currentColor document.getElementById("colo
    r").value
  • // don't send void messages
  • if (trim(oCurrentMessage.value) ! ""
  • trim(currentUser) ! "" trim
    (currentColor) ! "")
  • // if we need to send and retrieve messages
  • params "modeSendAndRetrieveNew"
  • "id" encodeURIComponent(lastMess
    ageID)
  • "color" encodeURIComponent(curre
    ntColor)
  • "name" encodeURIComponent(curren
    tUser)
  • "message" encodeURIComponent(oCu
    rrentMessage.value)
  • // add the message to the queue
  • cache.push(params)
  • // clear the text box
  • oCurrentMessage.value ""
Write a Comment
User Comments (0)
About PowerShow.com