This article is for those who want to make your own chat in php using ajax. In it I tell you about how to make a very simple chat.
That's how it looks.

Prerequisites:
1. Initial knowledge of php. Such as: How to connect to the database mysql?
2. Initial knowledge of html and css.
3. Initial knowledge in JavaScript and jQuery. (even if you only heard about jQuery, but it did not work with him)
So let's start!
First of all create a new database in MySQL and execute SQL query
CREATE TABLE `messages` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` char(255) character SET utf8 NOT NULL,
`text` text character SET utf8,
PRIMARY KEY (`id`)
);
In this table we have to be stored instant messages.
1. id - the message number, it should be marked as AUTO_INCREMENT in order that would be created for each message a unique index.
2. name - name of the user sending the message
3. text - the message itself
You can also expand the list of fields, such as time reports, and so on.
Now we create client side chat. It will be be realized in the file index.php:
<!-- Pointing DOCTYPE -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>PhpAjaxChat</title>
<!-- Everything works in UTF-8 -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- Load the styles for chat -->
<link rel="stylesheet" type="text/css" media="screen" href="css.css" />
<!-- Connecting jQuery -->
<script type="text/javascript" src="jquery.js"></script>
<!-- The very code of our chat -->
<script type="text/javascript">
$(document).ready(function () {
$("#pac_form").submit(Send); // hang on the form with the name and message event is triggered when pressed "Send" or "Enter"
$("#pac_text").focus(); // make focus on the box "the message"
setInterval("Load();", 2000); // create a timer that will trigger the download messages every 2 seconds (2000 milliseconds)
});
// Function to send a message
function Send() {
// Execute a query to the server using jquery ajax: $.post(address, {query parameters}, function that is called to complete the request)
$.post("ajax.php",
{
act: "send", // Tells the script that we send a new message and it should be written
name: $("#pac_name").val(), // username
text: $("#pac_text").val() // the text message
},
Load ); // to complete the dispatch call a function to download new messages Load()
$("#pac_text").val(""); // clean Message field
$("#pac_text").focus(); // and put a focus on it
return false; // very important from Send() return false. If you dont make it, sending of your form may happen , and the page will reboot
}
var last_message_id = 0; // number of the last message that user received
var load_in_process = false; // whether we can do is download messages. First is "false", it means - yes, we can
// Function to download messages
function Load() {
// Check whether we can download the message. This is done to ensure that we do not start the download again, if the old download is not over yet.
if(!load_in_process)
{
load_in_process = true; // Loading started
// refer the request to the server, which returns us javascript
$.post("ajax.php",
{
act: "load", // point out that it is downloading messages
last: last_message_id, // pass number of the last message that the user was last boot
rand: (new Date()).getTime()
},
function (result) { // this function as a parameter is passed javascript code, which we must comply
eval(result); // execute script from the server
$(".chat").scrollTop($(".chat").get(0).scrollHeight); // scrolls the message down
load_in_process = false; // say that downloading is over, we can now start a new download
});
}
}
</script>
<body>
<div style="padding: 100px;">
<h1>Php Ajax Chat</h1>
<!-- Here in these 2 div's Our message will go out of chat -->
<div class="chat r4">
<div id="chat_area"><!-- Here we will be adding new posts --></div>
</div>
<form id="pac_form" action=""><!-- Our form with name, message and a button to send -->
<table style="width: 100%;">
<tr>
<td>Name:</td>
<td>Message:</td>
<td></td>
</tr>
<tr>
<!-- The input field name -->
<td><input type="text" id="pac_name" class="r4" value="Guest"></td>
<!-- Message field -->
<td style="width: 80%;"><input type="text" id="pac_text" class="r4" value=""></td>
<!-- "Send" button-->
<td><input type="submit" value="Send"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
css.css:
* {
margin: 0;
padding: 0;
}
body {
font: normal normal normal 16px "Trebuchet MS", Arial, Times;
color: #000000;
}
/* Important property */
.chat {
height: 500px;
overflow: auto; /* This allows you to display the scrollbar */
position: relative; /* This allows you to move down the text in the layer, not stretching the page */
text-align: left;
border: solid #818181 1px;
}
.chat div {
position: absolute; /* Page remains the same size */
}
.chat span {
display: block;
}
input[type=text],textarea {
width: 100%;
font: normal normal normal 16px "Trebuchet MS", Arial, Times;
border: solid #818181 1px;
}
/* For CSS 3 */
.r4 {
-moz-border-radius: 4px;
-khtml-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
Now we'll create a server side of the chat ajax.php
<?php
// settings for connecting to MySQl
$config = array( 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'pacdb' );
// connecting to MySQL, if not work then leave
if( !mysql_connect($config['hostname'], $config['username'], $config['password']) )
{
exit();
}
// Select a database, if not work then leave
if( !mysql_select_db($config['dbname']) )
{
exit();
}
mysql_query("SET NAMES 'utf8'"); // tell MySQl that we will work with UTF-8
Header("Cache-Control: no-cache, must-revalidate"); // tell browser that he would not cache that page
Header("Pragma: no-cache");
Header("Content-Type: text/javascript; charset=utf-8"); // tell browser that it's javascript encoded UTF-8
// check whether there is a variable act (send or load), which shows us what to do
if( isset($_POST['act']) )
{
// $_POST['act'] - exists
switch ($_POST['act'])
{
case "send" : // if it is equal to send, call the function Send()
Send();
break;
case "load" : // if it is equal to the load, call the function Load()
Load();
break;
default : // if no to that and not another - leave
exit();
}
}
// The function performs the conservation message in the database
function Send()
{
// here we have two variables are referred to our java-script with the ajax
// it: $_POST['name'] - username
// и $_POST['text'] - Message
$name = substr($_POST['name'], 0, 200); // cut to 200 characters
$name = htmlspecialchars($name); // replace dangerous tags (<h1>, <br>, and others) to secure
$name = mysql_real_escape_string($name); // function escapes all special characters in unescaped_string, therefore, it can be safely used in the mysql_query ()
$text = substr($_POST['text'], 0, 200); // cut to 200 characters
$text = htmlspecialchars($text); // replace dangerous tags (<h1>, <br>, and others) to secure
$text = mysql_real_escape_string($text); // function escapes all special characters in unescaped_string, therefore, it can be safely used in the mysql_query ()
// add a new entry in the table messages
mysql_query("INSERT INTO messages (name,text) VALUES ('" . $name . "', '" . $text . "')");
}
// function performs download messages from the database and sending them to the user through the ajax a java-script
function Load()
{
// Here we have a variable passed to our java-script using ajax
// это: $_POST['last'] - number of the last message that the user has booted
$last_message_id = intval($_POST['last']); // returns an integer variable
// queries the database for 10 posts of the latest messages from more than $last_message_id
$query = mysql_query("SELECT * FROM messages WHERE ( id > $last_message_id ) ORDER BY id DESC LIMIT 10");
// check whether there are any new messages
if( mysql_num_rows($query) > 0 )
{
// begin forming javascript which we will pass to the client
$js = 'var chat = $("#chat_area");'; // obtain a "pointer" to the div, to which we add new posts
// following construction we get an array of messages from our query
$messages = array();
while ( $row = mysql_fetch_array($query) )
{
$messages[] = $row;
}
// record number of last message
// [0] - This returns us to the first element in the array $ messages, but as we have fulfilled a request with the parameter "DESC" (in reverse order)
// it turns number of the last message in the database
$last_message_id = $messages[0]['id'];
// are turning the array (now it is in the correct order)
$messages = array_reverse($messages);
// go on all the elements of the array $ messages
foreach ( $messages as $value )
{
// continue to generate a script to send to the user
$js .= 'chat.append("<span>' . $value['name'] . '» ' . $value['text'] . '</span>");'; // add message (<span>Name » text of the message</span>) in our div
}
$js .= "last_message_id = $last_message_id;"; // write the number of the last message received, and the next time start from this message
// send the code to the user, where it will be done with the function eval()
echo $js;
}
}
?>
Chat is ready! Congratulations!
Our sponsors:





