Ajax Chat


Hi and welcome.
In this tutorial im going to show and explain to you how to create a ajx chat application.

What is Ajax?
Simple, Ajax is a combination of several different programming tools to bulid interactive applications that are able to process the users request immediately, sort of like a software.

First, lets run this piece of SQL code on your database. We need to create a table to store all our information on...
PHP Code
  1. CREATE TABLE `chat` (
  2. `id` int(11) NOT NULL auto_increment,
  3. `username` varchar(25) NOT NULL default '',
  4. `message` text NOT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;


Okay lets now make the page where our main jax requests will go and xml stuff will all go inside...

We will call this page ajax_functions.js

ajax_functions.js snippet
PHP Code
  1. var xmlHttp //setting a var for the xmlhttp request
  2.  
  3. function chat(username) //creating the function...
  4. {
  5.  
  6. xmlHttp=GetXmlHttpObject() //setting the var to a real request
  7. if (xmlHttp==null) //if it cants get the xml object
  8. {
  9. alert ("Browser does not support HTTP Request") //tell the user
  10. return //dont do the rest of the script
  11. } //end of statement
  12. var url="chat.php" //where you want to send ur req to...
  13. url=url+"?q="+username //making it so u can fetch the data
  14. url=url+"&sid="+Math.random() //adding session id
  15. xmlHttp.onreadystatechange=stateChanged //get response
  16. xmlHttp.open("GET",url,true) //send it via get
  17. xmlHttp.send(null)
  18. }
  19.  
  20. function stateChanged() //function for getting response
  21. {
  22. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  23. {
  24. document.getElementById("text").innerHTML=xmlHttp.responseText //change ur div tag's inner html to the response text
  25. }
  26. }
  27.  
  28. function GetXmlHttpObject() //function to get xml object
  29. {
  30. var xmlHttp=null; //var is equal to nothing.
  31. try //attempt different browsers...
  32. {
  33. // Firefox, Opera 8.0+, Safari
  34. xmlHttp=new XMLHttpRequest(); //<--- for these three browsers set xmlobject to this.
  35. }
  36. catch (e) //if its ie then...
  37. {
  38. //Internet Explorer
  39. try
  40. {
  41. xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); //do this
  42. }
  43. catch (e)
  44. {
  45. xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  46. }
  47. }
  48. return xmlHttp; //send xml request to var running it
  49. }


Hope the comments helped u understand it.
Okay anyway thats our ajax_functions.js script complete.

Now its time to make the chat.php script which will process our request...

PHP Code
  1. <?
  2. //IMPORTANT
  3. //PUT UR DB CONNECTION HERE
  4.  
  5. if (isset($_GET['q'])){ //gets the request is there is any
  6. $get= mysql_query("SELECT * FROM chat ORDER BY id DESC LIMIT 20"); //get rows from chat and limit them to 20
  7. $get_num= mysql_num_rows($get); //how many rows are there?
  8.  
  9. if ($get_num == "0"){ //if there are no rows...
  10. $return="<u><b>N</b></u>obody is talking right now.";
  11. //return the above
  12. }else{ //otherwise
  13.  
  14. $return=""; //set $return to null
  15.  
  16. while ($the= mysql_fetch_object($get)){ //create a loop
  17. $return .= $the->message."";
  18. //get all the stuff from the db and echo the appropriate.
  19. } //end the loop
  20.  
  21. }} //end the statements
  22.  
  23. echo "$return"; //return the variable $return to the browser
  24. ?>


Okay now thats done.
Lets go on to our final page...
This page will be called mainpage.php
Its the page we will have our chat script on...

mainpage.php snippet
PHP Code
  1. <?
  2. //DB CONNECTION SCRIPT HERE INPORTANT!!!
  3. ?>
  4.  
  5. <script src="ajax_functions.js"></script>
  6. <!-- basically include the ajax_functions.js script -->
  7.  
  8. <script language="javascript">
  9. setInterval("chat()",3000);
  10. //make the function chat (from ajax_functions.js run every 3 seconds
  11. </script>
  12.  
  13. <b>Chat</b>
  14. <!-- below is our chat module... -->
  15. <div id="text" style="background-color:#009900; width:98%; padding:5; height:400;">
  16. Loading Village Chat...
  17. </div>
  18. <font color="#00FF00">Speak</font>
  19. <form method="post" name="talk">
  20. <select name="action" style="background-color:#009900; color:white; border:none;">
  21. <option value="talk">Talk</option>
  22. <option value="action">Action</option>
  23. </select>
  24. <!-- making the form -->
  25. Name: <input type="text" style="background-color:#009900; color:white; border:none; width:300;" name="username" />
  26. Text:
  27. <input type="text" style="background-color:#009900; color:white; border:none; width:300;" name="chat" />
  28. <a onclick="document.talk.submit();" style="cursor:pointer;"><u><b>S</b></u>peak</a> <a onclick="javascript:window.location.reload()" style="cursor:pointer;"><u><b>R</b></u>efresh</a>
  29.  
  30. <?
  31. if (strip_tags($_POST['chat']) && strip_tags($_POST['action']) && strip_tags($_POST['username']){
  32. $username= $_POST['username']; //get value
  33. $message= $_POST['chat']; //get values
  34. $action= $_POST['action']; //get values
  35. $message= htmlentities($message); //make it safe
  36. $username= htmlentities($username); //make it safe
  37.  
  38. if (empty($message)){ //if the message value is empty
  39. echo "An empty message?"; //alert the user
  40. }else{ //otherwise
  41.  
  42. if (strlen($message) > "100"){ //if message length if more than 100
  43. echo "<font color='red'>You can't speak for that long!</font>"; //alert the user
  44. }else{ //otherwise
  45.  
  46. $player_color= "black"; //maybe you want to change this?
  47.  
  48. if ($action == "action"){ //if they wanna do something
  49. $output="<font color=$player_color>$fetch->title $username</font> $message";
  50. }elseif ($action == "talk"){ //if they wanna just say something
  51. $output="<font color=$player_color>$fetch->title $username</font> says \"$message\"";
  52. }
  53.  
  54. mysql_query("INSERT INTO `chat` (`id` ,`username` ,`message`) VALUES ('' , '$username', '$output')"); //insert chat into db
  55.  
  56. }}} //end statements
  57. ?>


Remember to include ur db connection script aswell in this script and in the chat.php script.

I have commented the lines to make it much more simple. I hope tihs tutorial has helped you.

If there are any bugs then they will be fixed :D
Thanks, i will be putting a download link into the comments section as soon i get the script into a zip file etc.
ilyas-shezad's Avatar
Views:
3,086
Rating:
Posted on Friday 4th July 2008 at 04:52 PM
ilyas-shezad
ilyas-shezad's Avatar
I used bbcodes in that code and it really messed up :|
Dont use the function ill try getting a good one set up for yall.

If you cant be arsed then just dnt use te bbcode chat() parser function.
Posted on Friday 4th July 2008 at 04:51 PM
ilyas-shezad
ilyas-shezad's Avatar
Oh i see. Yeh that definately needs to be replaced. Or i can provide a function for that (its meant to be for parsing bbcodes).

If you dont need bbcodes in the the script then change:
Code
$return .= "".chat($the->message)."";

to
Code
$return .= "$the->message";


Otherwise at the beggining of your chat.php script, put this in...
Code
function chat($string){
$string= str_replace("", "<b>", $string);
$string= str_replace("", "<u>", $string);
$string= str_replace("
", "</b>", $string);
$string= str_replace("
", "</u>", $string);

$string .= "</b></u>"; //just for security
return $string;
}
Posted on Thursday 3rd July 2008 at 08:11 PM
DjMilez
DjMilez's Avatar
I think it's because of
Code
$return .= "".chat($the->message)."";

in chat.php =S
Posted on Tuesday 1st July 2008 at 10:54 AM
ilyas-shezad
ilyas-shezad's Avatar
Thats weird Dj. I never made or used a php function in all the scripts. I only used javascript functions.... any chance u can show demo of ur script?
Posted on Thursday 26th June 2008 at 08:55 PM
DjMilez
DjMilez's Avatar
Fatal error: Call to undefined function chat() in /home/djmilez/public_html/chat/chat.php on line 17
Posted on Thursday 12th June 2008 at 09:59 AM
ilyas-shezad
ilyas-shezad's Avatar
Yeh sorry about that i missed out a close bracket :| any chance you can edit that Shadow?
Posted on Thursday 12th June 2008 at 02:31 AM
ShadowMage
ShadowMage's Avatar
on line 31 if you copied and pasted replace with
Code
if (strip_tags($_POST['chat']) && strip_tags($_POST['action']) && strip_tags($_POST['username'])){
Posted on Thursday 12th June 2008 at 02:18 AM
Nathan
Nathan's Avatar
Parse error: syntax error, unexpected '{' in /home/rdlegend/public_html/rdlegends/includes/mainpage.php on line 26