How to implement an online chat in PHP with AJAX technology
In this article I make a brief presentation about the use of AJAX technology to implement a web chat. All the informations and the code that you can find in this article are revisions of some different code coming from several web sites.
The prerequisites needed to the understanding of this project:
- Html
- PHP
- Javascript
- AJAX tecnology
- SQL
First, we need six php files. The file names used in this project are:
- install.php
- connection.php
- welcome.php
- chat.php
- save.php
- show.php
The article is divided into the following six steps:
| STEP 1 || STEP 2 || STEP 3 || STEP 4 || STEP 5 || STEP 6 |
STEP 1: The first step to implement this project is the creation a Database and a Table in which all the written messages will be loaded. Thus, we create a php file called "install.php" to do this. In this file the following code must be written:
<?php
// Connection to the MySql Server
$host="your host";
$username="your username";
$password="your password";
$connection = @mysql_connect($host, $username, $password) or die ("Connection Error: ".mysql_error());
// Creating a Database
$database = "CREATE DATABASE database_name DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
if (mysql_query($database, $connection))
)
{
echo "Database created";
}
else
{
echo "Error creating Database: " . mysql_error();
}
//Creating a Table
mysql_select_db("database_name", $connection);
$table= "CREATE TABLE Chat (name varchar(10), message varchar(50), date int(10))";
if (mysql_query($table, $connection))
{
echo "Table created";
}
else
{
echo "Error creating Table: " . mysql_error();
}
// Closing Connection
mysql_close($connection)or die ("Closing Error: ".mysql_error());
?>
You can see that this code embeds some different instructions. The first one allows to connect to the MySQL Server. Thus, you must set the correct values for the variables: "host", "username" and "password". The second one allows to create a new Database while the third one to create a new Table in this Database. The final instruction closes the connection with the MySQL Server.
STEP 2: The second step is that of creating a php file that allows to connect to the Database created in the step 1. The "connection.php" file accomplishes this task with the following code:
<?php
// Connection parameters
$db_host = "your host";
$db_user = "your database";
$db_password = "your password";
$db_nome = "database_name";
// Connection to the MySql Server
$connection = @mysql_connect($db_host, $db_user, $db_password); or die("Connection Error: ".mysql_error());
// Connection to the Database
@mysql_select_db($db_nome, $connection) or die ("Error Database connection: " . mysql_error());
?>
The first part of this code is very similar to that shows in the first step. The only difference is the connection to the Database.
STEP 3: In this step we can see the code for the welcome page to the chat. Thus, the "welcome.php" file must have this code:
<?php
// Start new session
session_start();
?>
<!-- Form to enter the name that will identify the user -->
<!doctype html>
<html lang="en">
<head>
<title>Welcome to the chat</title>
</head>
<body>
<form action="#" method="post">
Enter a name <input type="text" name="name" />
<br/>
<input type="submit" value="Submit" name="submit" />
<br/>
</form>
<?php
// Check of data transmission
if ($_POST["submit"])
{
// Check for entering a name
if($_POST["name"])
{
$name = htmlspecialchars($_POST['name']);
$_SESSION['name'] = $name;
header("Location: chat.php", true);
}
else
{
echo "<br/>Enter a name!";
}
}
?>
</body>
</html>
The first part of the code opens a php session used to store the name entered by user. The code goes on with the html code about the form used to enter the name. In the final part of the code there is the php code that checks if the informations is sent from the form and if a name is entered by user.
STEP 4: The "chat.php" file is the heart of all the project. In fact, in this page there are both the form used to enter messages and all the asynchronous calls to the Server (see AJAX: acronym for Asynchronous JavaScript and XML). The code of "chat.php" file must be:
<?php
// Start new session
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<title>Chat</title>
<script type="text/javascript">
// Creation of XMLHttp objects to used for asynchronous calls
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Function to be executed when the page loads
window.onload=function(){
setInterval("show()",1000)
}
// Asynchronous loading of information from the "show.php" page to show in the "show" iframe
function show()
{
xmlhttp.open("GET","show.php",true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
FrameDocument("show").designMode = "On";
FrameDocument("show").body.innerHTML=unescape(xmlhttp.responseText);
FrameDocument("show").designMode = "Off";
}
}
}
// Enable writing of the "show" iframe (See "show" function)
function FrameDocument(iFrameID){
if (document.getElementById(iFrameID).contentDocument){
//Mozilla
return document.getElementById(iFrameID).contentDocument;
} else {
//ie
return document.frames[iFrameID].document;
}
}
// Asynchronous saving information sent by the form
function save()
{
xmlhttp.open("POST","save.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=<?php echo $_SESSION['name'] ?> &action="+escape(document.getElementById("action").value));
}
</script>
</head>
<body >
<div align="center">
<!-- The form used to enter and to watch messages-->
<form name="inclusion" method="post" onsubmit="javascript: save();document.getElementById('action').value=''; document.inclusion.action.focus();return false; ">
<iframe id="show" height='300px' width='400px'></iframe><br/>
<input name="action" id="action" size="50" autocomplete="off"/>
<input type="submit" value="Submit" name="submit"/>
</form>
</div>
</body>
</html>
The first part of the code resumes existing sessions used to memorize the name entered by user. After this code there are the html tags of the web page. In the head of this web page there is the heart of this project. In fact, you can find the Javascript code that manages the chat.
Before analyzing the javascript code it is better to look at the body of the page at the end of the code. In the body you can find the main form of the chat. This form embeds an iframe, a textbox and a button.The iframe is used to show the chat threads while the textbox to allow users to enter their messages and the button to send these. Whenever the button is pushed, the "save" function is called.
Now we can start to comment the javascript code. At the beginning there is the code used to instantiate the "XMLHttpRequest" object that allows to have the asynchronous calls. You can see this link to have more information about this topic.
The code continues with the management of the "window.onload". In fact, when the web page has finished loading, the "setInterval()" method will be used. This method allows us to call a function at specified intervals (see this link for more details). In our case the method calls the "show" function every second.
The "show" function send a request to the Server with the "open()" and "send()" methods of the "XMLHttpRequest" object (see this link for more informations). Thus, we have to wait the response by Server. The "onreadystatechange" event allows to manage this response. You can see this link to understand how to manage this event. In this case, when the response is ready, this text-response is updated in the "show" iframe. The "FrameDocument" function is called to write the iframe. in fact, the code to use changes according to the browser. Moreover, the "designmode" property is used in order to edit the document of the iframe.
STEP 5: The next step is creting the "save.php" file with the following code:
<?php
// Connection to the Server and Database Selection
include ("connection.php");
// Definition of the variables to enter in the Database
$name = $_POST['name'];
$time = time();
$mss = $_POST['action'];
// Data Entry
$query ="INSERT INTO Chat SET name = '$name', message = '$mss', date = '$time'";
@mysql_query($query) or die("Save Error: ".mysql_error());
// Closing Connection
mysql_close($connection);
?>
At the beginning of the code there is the inclusion of the "connection.php" file in order to connect to the Server and to select the Database (see Step 2). Then, we find the declaration of the variables to enter in the Database. The first and third variables take on the values sent with the POST method during the asynchronous call. These variables are used in the following query to the Database. Instead the second variable saves time when saving is done (this time will be useful in the Step 6). The code ends with the closing of the connection to the Database.
STEP 6: The final step is the creation of the "show.php" file. This file must have the following code:
<?php
// Connection to the Server and Database Selection
include ("connection.php");
// Current Time
$now = time();
// Data Selection
$query = "select * from Chat where date+3600>'$now' order by date desc";
$result = mysql_query($query) or die("Select Error: ".mysql_error());
// Extraction of data from the array
while($line = mysql_fetch_array($result)){
$name = stripslashes($line['name']);
$mss = stripslashes($line['message']);
$time = date("H:i", $line['data']);
echo $time." <strong>".$name."</strong> says: ".$mss."</br>";
}
// Closing the Connection
mysql_close($connection);
?>
The code start with the inclusion of the "connection.php" file in order to connect to the Server and to select the Database (see Step 2). Thus, there is the saving of the current time. This time is used in the following query to select all posts written in the last hour. All the selected fields are put in the "$result" array. Then, all data are extracted from the array and are returned. The code ends with the closing of the connection to the Database..
This article is only a guideline to understand how a chat service can be developed. In fact, many other important aspects must be considered in order to develop a real online chat. For example, the issues about SQL injections are not treated in this article. However, the aim of this article is to provide the basic code to develop a chat so you can modify it according to your needs.
If you find errors in this code, I will be very grateful if you report them to me. Thanks!