Blog posts
- Aug 26 - Shorten your long urls (0)
- Apr 13 - Photographing for ortographic view (0)
- Mar 31 - Add youtube search on your site (0)
- Dec 24 - Christmas and new year (0)
- Nov 11 - Redward sponsor VLP (0)
- Sep 09 - Texture Projection (0)
- Aug 03 - Backup files from Samba to a Desktop computer (1)
- Jul 25 - UbuntuInfo Script (1)
- Jul 06 - Create a chat using jquery and php (8)
Create a chat using jquery and php
Created Jul 06, 2009 22:31 by MarwellnThis blog post will show you how to create your own (simple) chat with html, jquery (javascript) and php.
Let's start by setting up our folder structure. The folder structure should look like this:
* /data/messages/
* /
The messages folder will contain all messages written. Well structured with folder for each month and files for each day inside the "month-folder". Don't forget to chmod the messages folder to 0777.
After that's complete, we can start building our chat by creating an index.php and styles.css file in the root. In those files, we're
going to build and decide how our layout should look like.
In the index file, add doctype, html, head and body tag like this:
As we are using jquery as our javascript library, we need to include the jquery file inside the head tags, and while we\'re at it, we\'re also going to
add a link to our own javascript file, style file and a mandatory title tag. Change the head tags to this:
The title tag can be changed, the link and the two script tags must remain as it is.
When that is done, we need to start designing our layout. In this example, we\'re going to use four divs, one as container, one for all messages, one
for text input and one to show that the text is being sent. Change the body tags to this:
The div with id container is mainly for centering the chat. The div with id chat-messages will, after calling an ajax query get the 25 (a user chosen
limit) latest messages. The div with id chat-send is what it looks like, it contains all input boxes and buttons, and the last div will show a loading message after pressing the enter key or the send button.
That's all the code for the index file. (Should look like this: http://www.redward.org/public/projects/chat/index.phps)
We're now going to start styling our website. Open up the styles.css file (create it if you haven\'t already). The first thing we're are going to do in the file is to chose a default font size and font type (family). We\'re also going to add some padding so the site is a bit from the wall. We're doing that with the following code (add it into the styles file):
Tahoma is a standard and a nice looking font, unfortunately it's not available in Linux (or at least Ubuntu), and that's why we're also using the FreeSans font which is pretty similar to Tahoma.
Next thing we're going to do is to make the chat 500 pixels wide and centered, using the following code:
Next is the div containing the messages and the div containing the input boxes and the input button:
The border-radius element is only for Firefox and Webkit (Chrome, Opera). It makes the corners round!
Next is the input boxes and the input button:
Nothing out of the ordinary with that. The loading div might be a bit trickier, it requires a absolute:relative; which can make the position a bit of if the width is changed. Following code is used:
It's hidden as standard, and that's why there's display:block;. It will be shown when pressing the enter key or the send button using our jquery code.
The last bit of code in the styles file is this:
This is used for each message row.
The style file is now complete and should look like this: http://www.redward.org/public/projects/chat/styles.txt
Now there's only three files left. chat.js, chat-msgs.php and chat.php. Lets start with opening the chat.js file (create it if you haven't already).
Add this in the file:
The keydown part gets the sendtext function when clicking the enter key. Same thing goes for the click event, it gets the sendtext function after pressing the send button. The getmessages function is used to get the 25 (user selected limit) latest messages.
After you've added the javascript code above, you're going to add three new functions. getmessages, getmess and sendtext. Add to following code to the file:
The getmessages function gets the messages via setTimeout and the getmess function every five seconds. The getmess function gets the messages with ajax post via a file called chat-msgs.php. The sendtext function checks if all required values are inserted and posts the message with ajax post via chat.php. The getmess function is called if the ajax post is successful.
Our javascript file, chat.js, is now complete and should look like this: http://www.redward.org/public/projects/chat/chat.txt
Next step ahead, open up chat-msgs.php (create it if you haven\'t already) and begin by adding these lines to the file:
If the file is called withour $_POST, it will die and nothing will be returned. The mess_output variable is set to null, else php would show an error while using the code below. The limit variable sets how many messages you want to be shown.
Next up is the getmessages function and the initie to it as well. This is the code:
The function search trough each folder for a maximum of 25 (your limit) hits or 20 folders. It then returns the value found from the files to an array.
The array is printed with a foreach loop together with the mess_output variable like this:
That's all for the chat-msgs.php file. The final result for that file should look like this: http://www.redward.org/public/projects/chat/chat-msgs.phps
Now there's only one file left. Open up chat.php (create it if you haven't already) and add this to the top of the file:
The first piece checks if user and message is set via post, if not, the file return false and dies. The curdate variable is like a shortcut. Instead of writing date two times, we use a variable named curdate.
Next up comes two function, one to change the text so it doesn\'t destroy the page and another for creating the text. This is the code:
The chatsend function is only used so you doesn't have to write the same piece of code twice.
The absolute last thing we're going to do is to add the following code to the file:
The code creates a directory and file automatically if it doesn't exists. If it exists it appends the message to the end of the file.
The file should now look like this: http://www.redward.org/public/projects/chat/chat.phps
The script can be downloaded from http://www.redward.org/public/projects/chat/chat.7z.
A preview of the script is found here: http://www.redward.org/public/projects/chat/
Let's start by setting up our folder structure. The folder structure should look like this:
* /data/messages/
* /
The messages folder will contain all messages written. Well structured with folder for each month and files for each day inside the "month-folder". Don't forget to chmod the messages folder to 0777.
After that's complete, we can start building our chat by creating an index.php and styles.css file in the root. In those files, we're
going to build and decide how our layout should look like.
In the index file, add doctype, html, head and body tag like this:
<?php
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' xml:lang='en'>
<head>
</head>
<body>
</body>
</html>";
?>
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' xml:lang='en'>
<head>
</head>
<body>
</body>
</html>";
?>
As we are using jquery as our javascript library, we need to include the jquery file inside the head tags, and while we\'re at it, we\'re also going to
add a link to our own javascript file, style file and a mandatory title tag. Change the head tags to this:
<head>
<title>Chat - Using jquery (javascript) and php (no database required)!</title>
<link rel='stylesheet' href='styles.css' type='text/css' media='screen' />
<script src='http://code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<script src='chat.js' type='text/javascript'></script>
</head>
<title>Chat - Using jquery (javascript) and php (no database required)!</title>
<link rel='stylesheet' href='styles.css' type='text/css' media='screen' />
<script src='http://code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<script src='chat.js' type='text/javascript'></script>
</head>
The title tag can be changed, the link and the two script tags must remain as it is.
When that is done, we need to start designing our layout. In this example, we\'re going to use four divs, one as container, one for all messages, one
for text input and one to show that the text is being sent. Change the body tags to this:
<body>
<div id='container'>
<!-- show messages -->
<div id='chat-messages'>
Loading messages...
</div>
<!-- send message formular -->
<div id='chat-send'>
<input type='text' id='send-user' />
<input type='text' id='send-text' />
<input type='button' id='send-text-button' value='Send' />
</div>
<div id='send-loading'>Loading...</div>
</div>
</body>
<div id='container'>
<!-- show messages -->
<div id='chat-messages'>
Loading messages...
</div>
<!-- send message formular -->
<div id='chat-send'>
<input type='text' id='send-user' />
<input type='text' id='send-text' />
<input type='button' id='send-text-button' value='Send' />
</div>
<div id='send-loading'>Loading...</div>
</div>
</body>
The div with id container is mainly for centering the chat. The div with id chat-messages will, after calling an ajax query get the 25 (a user chosen
limit) latest messages. The div with id chat-send is what it looks like, it contains all input boxes and buttons, and the last div will show a loading message after pressing the enter key or the send button.
That's all the code for the index file. (Should look like this: http://www.redward.org/public/projects/chat/index.phps)
We're now going to start styling our website. Open up the styles.css file (create it if you haven\'t already). The first thing we're are going to do in the file is to chose a default font size and font type (family). We\'re also going to add some padding so the site is a bit from the wall. We're doing that with the following code (add it into the styles file):
* { margin:0; padding:0; }
html {
font-size:11px;
font-family:Tahoma, FreeSans;
padding:10px;
}
html {
font-size:11px;
font-family:Tahoma, FreeSans;
padding:10px;
}
Tahoma is a standard and a nice looking font, unfortunately it's not available in Linux (or at least Ubuntu), and that's why we're also using the FreeSans font which is pretty similar to Tahoma.
Next thing we're going to do is to make the chat 500 pixels wide and centered, using the following code:
/* div container */
#container {
width:500px;
margin:0 auto;
text-align:center; /* centering fix for ie */
}
#container {
width:500px;
margin:0 auto;
text-align:center; /* centering fix for ie */
}
Next is the div containing the messages and the div containing the input boxes and the input button:
/* list messages div */
#chat-messages {
border:1px solid gray;
-moz-border-radius-topleft:5px;
-webkit-border-top-left-radius:5px;
padding:2px;
text-align:left;
word-wrap:break-word;
}
/* send div */
#chat-send {
border:1px solid gray;
border-top:none;
-moz-border-radius-bottomright:5px;
-webkit-border-bottom-right-radius:5px;
padding:2px;
text-align:left;
}
#chat-messages {
border:1px solid gray;
-moz-border-radius-topleft:5px;
-webkit-border-top-left-radius:5px;
padding:2px;
text-align:left;
word-wrap:break-word;
}
/* send div */
#chat-send {
border:1px solid gray;
border-top:none;
-moz-border-radius-bottomright:5px;
-webkit-border-bottom-right-radius:5px;
padding:2px;
text-align:left;
}
The border-radius element is only for Firefox and Webkit (Chrome, Opera). It makes the corners round!
Next is the input boxes and the input button:
/* the send input box */
#send-text {
width:324px;
font-size:inherit;
font-family:inherit;
border:1px solid #ececec;
}
#send-user {
width:100px;
font-size:inherit;
font-family:inherit;
border:1px solid #ececec;
}
/* the send input button */
#send-text-button {
font-size:11px; /* must enter values for IE7 */
font-family:Tahoma, FreeSans; /* must enter values for IE7 */
width:60px;
}
#send-text {
width:324px;
font-size:inherit;
font-family:inherit;
border:1px solid #ececec;
}
#send-user {
width:100px;
font-size:inherit;
font-family:inherit;
border:1px solid #ececec;
}
/* the send input button */
#send-text-button {
font-size:11px; /* must enter values for IE7 */
font-family:Tahoma, FreeSans; /* must enter values for IE7 */
width:60px;
}
Nothing out of the ordinary with that. The loading div might be a bit trickier, it requires a absolute:relative; which can make the position a bit of if the width is changed. Following code is used:
#send-loading {
position:relative;
top:-20px;
text-align:right;
right:70px;
color:gray;
display:none;
}
position:relative;
top:-20px;
text-align:right;
right:70px;
color:gray;
display:none;
}
It's hidden as standard, and that's why there's display:block;. It will be shown when pressing the enter key or the send button using our jquery code.
The last bit of code in the styles file is this:
.mess-holder { padding:2px; }
.mess-holder:hover { background:#ececec; }
/* set divs to inline */
.mess-holder div {
display:inline;
}
.mess-holder:hover { background:#ececec; }
/* set divs to inline */
.mess-holder div {
display:inline;
}
This is used for each message row.
The style file is now complete and should look like this: http://www.redward.org/public/projects/chat/styles.txt
Now there's only three files left. chat.js, chat-msgs.php and chat.php. Lets start with opening the chat.js file (create it if you haven't already).
Add this in the file:
$(document).ready(function(){
getmessages();
$('#send-text-button').click(function(event){
sendtext();
});
});
$(window).keydown(function(event){
var kC = event.keyCode;
if (kC == 13) { /* when pressing the 'enter' key */
sendtext();
}
});
getmessages();
$('#send-text-button').click(function(event){
sendtext();
});
});
$(window).keydown(function(event){
var kC = event.keyCode;
if (kC == 13) { /* when pressing the 'enter' key */
sendtext();
}
});
The keydown part gets the sendtext function when clicking the enter key. Same thing goes for the click event, it gets the sendtext function after pressing the send button. The getmessages function is used to get the 25 (user selected limit) latest messages.
After you've added the javascript code above, you're going to add three new functions. getmessages, getmess and sendtext. Add to following code to the file:
function getmessages() {
getmess();
setTimeout("getmessages()", 5000);
}
function getmess() {
$.ajax({
type: 'post',
url: 'chat-msgs.php',
data: { iCHAT: true },
error: function (data) {
alert("Error occoured while trying to get messages: "+data);
},
success: function (data) {
$('#chat-messages').html(data);
}
});
}
function sendtext() {
var x = $('#send-text').val();
var y = $('#send-user').val();
if (y == '') { alert('Please enter a username before posting.'); }
if (x != '' && y != '') {
$.ajax({
type: 'post',
url: 'chat.php',
data: { message: x, user: y },
beforeSend: function () {
$('#send-loading').html('Loading...');
$('#send-loading').show();
},
error: function (data) {
alert('Error occoured: '+data);
$('#send-loading').html('Error occoured.');
},
success: function (data) {
$('#send-loading').hide();
$('#send-text').val('');
getmess();
}
});
}
}
getmess();
setTimeout("getmessages()", 5000);
}
function getmess() {
$.ajax({
type: 'post',
url: 'chat-msgs.php',
data: { iCHAT: true },
error: function (data) {
alert("Error occoured while trying to get messages: "+data);
},
success: function (data) {
$('#chat-messages').html(data);
}
});
}
function sendtext() {
var x = $('#send-text').val();
var y = $('#send-user').val();
if (y == '') { alert('Please enter a username before posting.'); }
if (x != '' && y != '') {
$.ajax({
type: 'post',
url: 'chat.php',
data: { message: x, user: y },
beforeSend: function () {
$('#send-loading').html('Loading...');
$('#send-loading').show();
},
error: function (data) {
alert('Error occoured: '+data);
$('#send-loading').html('Error occoured.');
},
success: function (data) {
$('#send-loading').hide();
$('#send-text').val('');
getmess();
}
});
}
}
The getmessages function gets the messages via setTimeout and the getmess function every five seconds. The getmess function gets the messages with ajax post via a file called chat-msgs.php. The sendtext function checks if all required values are inserted and posts the message with ajax post via chat.php. The getmess function is called if the ajax post is successful.
Our javascript file, chat.js, is now complete and should look like this: http://www.redward.org/public/projects/chat/chat.txt
Next step ahead, open up chat-msgs.php (create it if you haven\'t already) and begin by adding these lines to the file:
<?php
/* die if post iCHAT not set */
if (!isset($_POST['iCHAT']) || $_POST['iCHAT'] != true) { die(); }
/* reset variables */
$mess_output = null;
$limit = 25; // max 25 messages shown
/* die if post iCHAT not set */
if (!isset($_POST['iCHAT']) || $_POST['iCHAT'] != true) { die(); }
/* reset variables */
$mess_output = null;
$limit = 25; // max 25 messages shown
If the file is called withour $_POST, it will die and nothing will be returned. The mess_output variable is set to null, else php would show an error while using the code below. The limit variable sets how many messages you want to be shown.
Next up is the getmessages function and the initie to it as well. This is the code:
/* check through files and folders function */
function getmessages($day, $b, $i) {
global $messages, $limit;
$time = strtotime("$day day");
$dat['day'] = date('j', $time);
$dat['month'] = date('m', $time);
$dat['year'] = date('Y', $time);
$dir = "data/messages/".$dat['year']."-".$dat['month'];
$file = $dat['day'].".php";
if (file_exists($dir."/".$file)) {
$mess_string = file_get_contents($dir."/".$file);
$mess[$dir."/".$file] = simplexml_load_string("<?xml version='1.0'?><document>$mess_string</document>");
foreach ($mess[$dir."/".$file]->item as $mss) {
$date = explode(" ", $mss->date);
$messages[$date['1']] = "<div class='mess-holder'>
<div class='mess-date'>(".date("Y-m-d H:i:s", $date['1']).")</div>
<div class='mess-user'><".$mss->user."></div>
<div class='mess-body'>".$mss->body."</div>
</div>";
++$i;
}
if (count($messages) < $limit) getmessages($day-1, $b, $i);
} else {
if ($b <= 40) {
++$b;
getmessages($day-1, $b, $i);
} else {
return false;
}
}
}
/* initiate message-get */
getmessages(date('j'), 0, 0);
function getmessages($day, $b, $i) {
global $messages, $limit;
$time = strtotime("$day day");
$dat['day'] = date('j', $time);
$dat['month'] = date('m', $time);
$dat['year'] = date('Y', $time);
$dir = "data/messages/".$dat['year']."-".$dat['month'];
$file = $dat['day'].".php";
if (file_exists($dir."/".$file)) {
$mess_string = file_get_contents($dir."/".$file);
$mess[$dir."/".$file] = simplexml_load_string("<?xml version='1.0'?><document>$mess_string</document>");
foreach ($mess[$dir."/".$file]->item as $mss) {
$date = explode(" ", $mss->date);
$messages[$date['1']] = "<div class='mess-holder'>
<div class='mess-date'>(".date("Y-m-d H:i:s", $date['1']).")</div>
<div class='mess-user'><".$mss->user."></div>
<div class='mess-body'>".$mss->body."</div>
</div>";
++$i;
}
if (count($messages) < $limit) getmessages($day-1, $b, $i);
} else {
if ($b <= 40) {
++$b;
getmessages($day-1, $b, $i);
} else {
return false;
}
}
}
/* initiate message-get */
getmessages(date('j'), 0, 0);
The function search trough each folder for a maximum of 25 (your limit) hits or 20 folders. It then returns the value found from the files to an array.
The array is printed with a foreach loop together with the mess_output variable like this:
$i = 0;
if (isset($messages)) {
rsort($messages);
foreach ($messages as $msgskey => $msgsval) {
if ($i <= $limit) {
$mess_output = $msgsval.$mess_output;
}
++$i;
}
}
echo (isset($messages) ? $mess_output : 'No messages written yet.');
?>
if (isset($messages)) {
rsort($messages);
foreach ($messages as $msgskey => $msgsval) {
if ($i <= $limit) {
$mess_output = $msgsval.$mess_output;
}
++$i;
}
}
echo (isset($messages) ? $mess_output : 'No messages written yet.');
?>
That's all for the chat-msgs.php file. The final result for that file should look like this: http://www.redward.org/public/projects/chat/chat-msgs.phps
Now there's only one file left. Open up chat.php (create it if you haven't already) and add this to the top of the file:
<?php
$messageCheck = (isset($_POST['message']) ? str_replace(" ", "", $_POST['message']) : null);
$userCheck = (isset($_POST['user']) ? str_replace(" ", "", $_POST['user']) : null);;
/* die if message or user is not set or empty */
if (!isset($messageCheck) || empty($messageCheck) || !isset($userCheck) || empty($userCheck)) {
return false;
die();
}
/* set curdate variabel */
$curdate = date('Y')."-".date('m');
$messageCheck = (isset($_POST['message']) ? str_replace(" ", "", $_POST['message']) : null);
$userCheck = (isset($_POST['user']) ? str_replace(" ", "", $_POST['user']) : null);;
/* die if message or user is not set or empty */
if (!isset($messageCheck) || empty($messageCheck) || !isset($userCheck) || empty($userCheck)) {
return false;
die();
}
/* set curdate variabel */
$curdate = date('Y')."-".date('m');
The first piece checks if user and message is set via post, if not, the file return false and dies. The curdate variable is like a shortcut. Instead of writing date two times, we use a variable named curdate.
Next up comes two function, one to change the text so it doesn\'t destroy the page and another for creating the text. This is the code:
/* fix post variables */
function stripinput($val) {
$replace = array("<", ">", "&");
$with = array("<", ">", "&");
$val = str_replace($replace, $with, $val);
return $val;
}
/* write function */
function chatsend($newfile=false) {
$res = ($newfile ? '' : "\n")
."\t<item>
<user>".stripinput($_POST['user'])."</user>
<date>".microtime()."</date>
<body>".stripinput($_POST['message'])."</body>
<ip>".$_SERVER['REMOTE_ADDR']."</ip>
</item>";
return $res;
}
function stripinput($val) {
$replace = array("<", ">", "&");
$with = array("<", ">", "&");
$val = str_replace($replace, $with, $val);
return $val;
}
/* write function */
function chatsend($newfile=false) {
$res = ($newfile ? '' : "\n")
."\t<item>
<user>".stripinput($_POST['user'])."</user>
<date>".microtime()."</date>
<body>".stripinput($_POST['message'])."</body>
<ip>".$_SERVER['REMOTE_ADDR']."</ip>
</item>";
return $res;
}
The chatsend function is only used so you doesn't have to write the same piece of code twice.
The absolute last thing we're going to do is to add the following code to the file:
/* check if folder exists */
if (is_dir("data/messages/$curdate")) {
if (file_exists("data/messages/$curdate/".date('j').".php")) {
$fp = fopen("data/messages/$curdate/".date('j').".php", "a+");
fwrite($fp, chatsend());
fclose($fp);
} else {
$fp = fopen("data/messages/$curdate/".date('j').".php", "w+");
fwrite($fp, chatsend(true));
fclose($fp);
}
} else {
/* create dir if not found */
mkdir("data/messages/$curdate", 0755);
fopen("data/messages/$curdate/index.php", "w+");
$fp = fopen("data/messages/$curdate/".date('j').".php", "w+");
fwrite($fp, chatsend(true));
fclose($fp);
}
?>
if (is_dir("data/messages/$curdate")) {
if (file_exists("data/messages/$curdate/".date('j').".php")) {
$fp = fopen("data/messages/$curdate/".date('j').".php", "a+");
fwrite($fp, chatsend());
fclose($fp);
} else {
$fp = fopen("data/messages/$curdate/".date('j').".php", "w+");
fwrite($fp, chatsend(true));
fclose($fp);
}
} else {
/* create dir if not found */
mkdir("data/messages/$curdate", 0755);
fopen("data/messages/$curdate/index.php", "w+");
$fp = fopen("data/messages/$curdate/".date('j').".php", "w+");
fwrite($fp, chatsend(true));
fclose($fp);
}
?>
The code creates a directory and file automatically if it doesn't exists. If it exists it appends the message to the end of the file.
The file should now look like this: http://www.redward.org/public/projects/chat/chat.phps
The script can be downloaded from http://www.redward.org/public/projects/chat/chat.7z.
A preview of the script is found here: http://www.redward.org/public/projects/chat/
Comments
Marwelln
March 27, 2010 :: 18:51
My demo works fine. There is no problem with it. Having hard seeing the two fields?
Don't forget to chmod your data/messages/ folder if you're in a non-windows environment.
Don't forget to chmod your data/messages/ folder if you're in a non-windows environment.
no demo
March 27, 2010 :: 03:22
Your demo doesn't ask for a name and doesn't work. The code also fails in my tests
Marwelln
November 04, 2009 :: 19:21
Have you made the /data/messages/ folder and chmodded it to 0777?
dloogie
October 25, 2009 :: 22:33
Error occoured while trying to get messages: [object XMLHttpRequest]
Any ideas??
Any ideas??
Marwelln
August 29, 2009 :: 19:32
You need to chmod /data/messages to 0777.
pre
August 28, 2009 :: 21:44
Koo I got that fix but now It just says No Messages written yet, no matter how many messages I type in
pre
August 28, 2009 :: 21:18
Hello, I'm getting an error stating WARNING: mkdir()[funtion.mkdir]: NO such file or directory
how can I fix this please.
how can I fix this please.
soon
August 27, 2009 :: 02:57
simple and easy to learn!. good.
![[www.korturl.com]p_korturl.png](plugins/gallery/images/Partners/[www.korturl.com]p_korturl.png)
![[www.anrdoezrs.net(slash)click-3898058-10645381]p_beniro.png](plugins/gallery/images/Partners/[www.anrdoezrs.net(slash)click-3898058-10645381]p_beniro.png)
![[www.vispark.se]p_vispark.png](plugins/gallery/images/Partners/[www.vispark.se]p_vispark.png)