PHP Ajax chat tutorial

In this tutorial you will learn how to create your own chat using php, mysql and ajax technology . This is the basic tutorial of working browser chat , and it will work great on any existing PHP based website , or as a stand alone chat website. First consider which folder will contain your ajax chat files . In this tutorial we will store all the files in the folder named : ajaxchat
1. Create database “chat” using your mysqladmin and create table chat :
CREATE TABLE chat
(
chat_id int(11) NOT NULL auto_increment,
posted_on datetime NOT NULL,
user_name varchar(255) NOT NULL,
message text NOT NULL,
PRIMARY KEY (chat_id)
);
2. create file named “__CONFIG.php” and enter following code into by changing database fields and website_url field to your url
<?php
if ($_SERVER["HTTP_HOST"] == “localhost”)
{
error_reporting(E_ALL ^ E_NOTICE);
}
session_start();
// Website Settings
//*********************************************************************************
define(”WEBSITE_URL”, “your_website_url”);
define(”WEBSITE_ROOT”, $_SERVER["DOCUMENT_ROOT"].”ajaxchat”);
//Database Settings – change it
//*********************************************************************************
if ($_SERVER["HTTP_HOST"] == “localhost”)
{
define(”DB_HOST”, “localhost”);
define(”DB_NAME”, “chat”);
define(”DB_USER”, “your_database_username”);
define(”DB_PASS”, “database_password”);
}
?>
3. Create file __init.php and insert the following code into it :
<?php
include_once “__CONFIG.php”;
// Includes the necessary class files from classes directory automatically
//*********************************************************************************
function __autoload($className)
{
include_once(WEBSITE_ROOT. “/classes/class.” . strtolower($className) .”.php”);
}
$dbconnect = new Dbconnect();
$mysql = new Mysql();
?>
4. Create file index.php and insert following code into :
<?php
include “__init.php”;
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html>
<head>
<title>glurt ajax chat</title>
<link rel=”stylesheet” type=”text/css” href=”css/style.css” />
<script type=”text/javascript” src=”js/async.js”></script>
<script type=”text/javascript” src=”js/switcher1.js”></script>
</head>
<body onload=”process()”>
<table align=”center” cellpadding=”0″ cellspacing=”0″>
<tr>
<td>
<h1>$implex ajax chat</h1>
</td>
</tr>
<tr>
<td>
<div id=”myDivElement” ></div>
</td>
</tr>
<tr>
<td>
<div>
<?php
if(isset($_SESSION['username']))
{
?>
<form action=”javascript:get(document.getElementById(’myform’));” name=”myform” >
<input type=”text” name=”ctxt” />
<input type=”button” name=”button” value=”Submit” onclick=”javascript:get(this.parentNode);” />
</form>
<?
}else{
?>
<form action=”set_username.php” method=”post”>
<b>Type your username below :</b><br/>
<input type=”text” name=”username” />
<input type=”submit” name=”button” value=”Start chatting” />
<input type=”hidden” name=”action” value=”1″ />
</form>
<?
}
?>
</div>
</td>
</tr>
<tr>
<td style=”text-align:center;font-size:7pt;padding-top:2em;”>
<a href=”http://glurt.com”>Powered by GLURT</a>
</td>
</tr>
</table>
</body>
</html>
5. Now we need the process file to set username for our ajax chat . create file set_username.php and insert this code into
<?php
include “__init.php”;
if(isset($_POST['action']) && $_POST['action']==1)
{
$_SESSION['username'] = strip_tags(addslashes($_POST['username']));
header(”location:”.WEBSITE_URL);
}
?>
6. Create folder ajaxfiles , create new file called chat.php , this file has properties to read the chat entries from the database , and called by ajax asynchroneous request :
<?php
include “../__init.php”;
$sql = “select user_name,message,posted_on from chat order by chat_id desc limit 10″;
$query = $mysql->query($sql);
while ($row = $mysql->fetchArray($query))
{
$text = preg_replace(”#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise”, “‘\\1<a href=\”\\2\” target=\”__blank\”>\\2</a>’”, $row['message']);
$text = preg_replace(”#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#ise”, “‘\\1<a href=\”http://\\2\” target=\”__blank\”>\\2</a>’”, $text);
$time = $row['posted_on'];
$time_format = strftime(”%a %d %b %H:%M:%S %Y”, strtotime($time));
echo “<b>”.$row['user_name'].”</b> <span style=’font-size:8pt;’>(”.$time_format.”)</span>: “.$text. “<br/><br/>”;
}
?>
7. in folder ajaxfiles create file named saveEntry.php , this file is for ajax saving entry request :
<?php
include “../__init.php”;
$username = strip_tags(addslashes($_SESSION['username']));
$chat_entry = strip_tags(addslashes($_GET['ctxt']));
$sql = “insert into chat (posted_on,user_name,message) values(now(),’$username’,'$chat_entry’)”;
$mysql->query($sql);
?>
8. Now we need database connection properties . Create folder named classes and create file named class.dbconnect.php , insert following code into it :
<?php
class Dbconnect
{
public function __construct()
{
mysql_connect(DB_HOST,DB_USER,DB_PASS) OR die(”Unable to connect to Database”);
mysql_select_db(DB_NAME) OR DIE(”Unable to select database”);
}
public function __destruct()
{
mysql_close();
}
}
?>
9. Another class for the mysql database with mysql function , create file named class.mysql.php in classes folder , and insert the following code into it
<?php
class Mysql
{
public function query($sql)
{
if ($_SERVER["HTTP_HOST"] == “localhost”)
{
$query = mysql_query($sql) or die($sql . “<br />” . mysql_error());
}
else
{
$query = mysql_query($sql) or die($sql . “<br />” . mysql_error());
}
return $query;
}
public function fetchArray($query)
{
$row= mysql_fetch_assoc($query);
return $row;
}
public function rowCount($query)
{
$count = mysql_num_rows($query);
return $count;
}
public function affectedRows()
{
return mysql_affected_rows();
}
}
?>
10. Now we need to create ajax procedures for our php scripts . Create folder js in main directory, and create file named async.js this file re executes the database checking every 500 miliseconds to check if there are new entries , insert following code into it :
var updateInterval = 1;
// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// 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.XMLHTTP.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 i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
{
try
{
// try to create XMLHttpRequest object
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e) {}
}
}
// return the created object or display an error message
if (!xmlHttp)
alert(”Error creating the XMLHttpRequest object.”);
else
return xmlHttp;
}
// called to read a file from the server
function process()
{
// only continue if xmlHttp isn’t void
if (xmlHttp)
{
// try to connect to the server
try
{
// initiate reading the async.txt file from the server
xmlHttp.open(”GET”, “ajaxfiles/chat.php”, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
// display the error in case of failure
catch (e)
{
alert(”Can’t connect to server:\n” + e.toString());
}
}
}
// function that handles the HTTP response
function handleRequestStateChange()
{
// obtain a reference to the <div> element on the page
myDiv = document.getElementById(”myDivElement”);
// display the status of the request
// when readyState is 4, we also read the server response
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 1)
{
// continue only if HTTP status is “OK”
if (xmlHttp.status == 200)
{
try
{
// read the message from the server
response = xmlHttp.responseText;
// display the message
myDiv.innerHTML = response;
setTimeout(”process();”, updateInterval * 700);
}
catch(e)
{
// display error message
alert(”Error reading the response: ” + e.toString());
}
}
else
{
// display status message
alert(”There was a problem retrieving the data:\n” +
xmlHttp.statusText);
}
}
}
11. in same folder js create file named switcher1.js , this file handles form submission, inset following code into it :
var http_request = false;
function makeRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,…
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType(’text/xml’);
http_request.overrideMimeType(’text/html’);
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject(”Msxml2.XMLHTTP”);
} catch (e) {
try {
http_request = new ActiveXObject(”Microsoft.XMLHTTP”);
} catch (e) {}
}
}
if (!http_request) {
alert(’Cannot create XMLHTTP instance’);
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open(’GET’, url + parameters, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById(’myspan’).innerHTML = result;
} else {
alert(’There was a problem with the request.’);
}
}
}
function get(obj) {
var getstr = “?”;
for (i=0; i<obj.childNodes.length; i++) {
if (obj.childNodes[i].tagName == “INPUT”) {
if (obj.childNodes[i].type == “text”) {
getstr += obj.childNodes[i].name + “=” + obj.childNodes[i].value + “&”;
}
if (obj.childNodes[i].type == “checkbox”) {
if (obj.childNodes[i].checked) {
getstr += obj.childNodes[i].name + “=” + obj.childNodes[i].value + “&”;
} else {
getstr += obj.childNodes[i].name + “=&”;
}
}
if (obj.childNodes[i].type == “radio”) {
if (obj.childNodes[i].checked) {
getstr += obj.childNodes[i].name + “=” + obj.childNodes[i].value + “&”;
}
}
}
if (obj.childNodes[i].tagName == “SELECT”) {
var sel = obj.childNodes[i];
getstr += sel.name + “=” + sel.options[sel.selectedIndex].value + “&”;
}
}
makeRequest(’ajaxfiles/saveEntry.php’, getstr);
}
12. Now let’s style our html , create folder named css and create file style.css in css folder :
body
{padding:0px; margin:0px 0px 0px 0px; font-size:10pt; font-family:Arial,Verdana,Tahoma,Helvetica,sans-serif;}
#myDivElement{overflow-y: scroll;height:200px;width:700px;border:1px solid #ccc;padding:1em;}
div.textArea{
margin-top:1em;
}
input.textWrite{
width:600px;
}
input.submitButton{
width:120px;
border:1px solid #ccc;
background:#39849d;
color:white;
font-weight:bold;
}
table.mainTab{ vertical-align:middle;}
That’s it , our ajax chat done . You may make it more complex by adding additional classes , javascript code and users registration tables .
Good luck.
