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...
CREATE TABLE `chat` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(25) NOT NULL default '',
`message` text NOT NULL,
PRIMARY KEY (`id`)
) 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
var xmlHttp //setting a var for the xmlhttp request
function chat(username) //creating the function...
{
xmlHttp=GetXmlHttpObject() //setting the var to a real request
if (xmlHttp==null) //if it cants get the xml object
{
alert ("Browser does not support HTTP Request") //tell the user
return //dont do the rest of the script
} //end of statement
var url="chat.php" //where you want to send ur req to...
url=url+"?q="+username //making it so u can fetch the data
url=url+"&sid="+Math.random() //adding session id
xmlHttp.onreadystatechange=stateChanged //get response
xmlHttp.open("GET",url,true) //send it via get
xmlHttp.send(null)
}
function stateChanged() //function for getting response
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("text").innerHTML=xmlHttp.responseText //change ur div tag's inner html to the response text
}
}
function GetXmlHttpObject() //function to get xml object
{
var xmlHttp=null; //var is equal to nothing.
try //attempt different browsers...
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest(); //<--- for these three browsers set xmlobject to this.
}
catch (e) //if its ie then...
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); //do this
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp; //send xml request to var running it
}
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...
<?
//IMPORTANT
//PUT UR DB CONNECTION HERE
if (isset($_GET['q'])){ //gets the request is there is any
$get= mysql_query("SELECT * FROM chat ORDER BY id DESC LIMIT 20"); //get rows from chat and limit them to 20
$get_num= mysql_num_rows($get); //how many rows are there?
if ($get_num == "0"){ //if there are no rows...
$return="<u><b>N</b></u>obody is talking right now.";
//return the above
}else{ //otherwise
$return=""; //set $return to null
while ($the= mysql_fetch_object($get)){ //create a loop
$return .= $the->message."";
//get all the stuff from the db and echo the appropriate.
} //end the loop
}} //end the statements
echo "$return"; //return the variable $return to the browser
?>
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
<?
//DB CONNECTION SCRIPT HERE INPORTANT!!!
?>
<script src="ajax_functions.js"></script>
<!-- basically include the ajax_functions.js script -->
<script language="javascript">
setInterval("chat()",3000);
//make the function chat (from ajax_functions.js run every 3 seconds
</script>
<b>Chat</b>
<!-- below is our chat module... -->
<div id="text" style="background-color:#009900; width:98%; padding:5; height:400;">
Loading Village Chat...
</div>
<font color="#00FF00">Speak</font>
<form method="post" name="talk">
<select name="action" style="background-color:#009900; color:white; border:none;">
<option value="talk">Talk</option>
<option value="action">Action</option>
</select>
<!-- making the form -->
Name: <input type="text" style="background-color:#009900; color:white; border:none; width:300;" name="username" />
Text:
<input type="text" style="background-color:#009900; color:white; border:none; width:300;" name="chat" />
<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>
<?
if (strip_tags($_POST['chat']) && strip_tags($_POST['action']) && strip_tags($_POST['username']){
$username= $_POST['username']; //get value
$message= $_POST['chat']; //get values
$action= $_POST['action']; //get values
$message= htmlentities($message); //make it safe
$username= htmlentities($username); //make it safe
if (empty($message)){ //if the message value is empty
echo "An empty message?"; //alert the user
}else{ //otherwise
if (strlen($message) > "100"){ //if message length if more than 100
echo "<font color='red'>You can't speak for that long!</font>"; //alert the user
}else{ //otherwise
$player_color= "black"; //maybe you want to change this?
if ($action == "action"){ //if they wanna do something
$output="<font color=$player_color>$fetch->title $username</font> $message";
}elseif ($action == "talk"){ //if they wanna just say something
$output="<font color=$player_color>$fetch->title $username</font> says \"$message\"";
}
mysql_query("INSERT INTO `chat` (`id` ,`username` ,`message`) VALUES ('' , '$username', '$output')"); //insert chat into db
}}} //end statements
?>
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.
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.
If you dont need bbcodes in the the script then change:
to
Otherwise at the beggining of your chat.php script, put this in...
$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;
}
in chat.php =S