Forgot Password / Register
Site Statistics
Total Members: 510
Total Tutorials: 242
Newsest User: Hp
Todays Unique Hits: 121
0 Users 1 Guests Online

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...
Code

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
Code

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...

PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?
//IMPORTANT
//PUT UR DB CONNECTION HERE

if (isset($_GET['q'])){ //gets the request is there is any
$getmysql_query("SELECT * FROM chat ORDER BY id DESC LIMIT 20"); //get rows from chat and limit them to 20
$get_nummysql_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 ($themysql_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
PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?
//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
$messagehtmlentities($message); //make it safe
$usernamehtmlentities($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.
ilyas-shezad
Views:
2172
Rating:
Posted on Friday 4th July 2008 at 04:52 PM
ilyas-shezad
ilyas-shezad
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
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
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
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
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
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
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
Parse error: syntax error, unexpected '{' in /home/rdlegend/public_html/rdlegends/includes/mainpage.php on line 26