Jump to content

How to create a live chat box


KenBrace

Recommended Posts

This will be a guide on how to create a basic chat box with live feed. The technologies used will be HTML, CSS, PHP, & Javascript. We will also be using a little jQuery. If you do not have at least a basic understanding of these languages then you'll have a hard time understanding this tutorial.

 

The first thing you will need to do is set up the database.

 

Create a database table titled "chat". Give it the following structure.

 

id INT(11) NOT NULL AUTO_INCREMENT

message VARCHAR(255) NOT NULL

time_sent DATETIME NOT NULL

 

Give the table a primary key of "id".

 

If you have any questions about this just post here in the thread and ask. I'll help you out if I can.

 

Once you've done this you will need to create your main page. I'm calling mine "chatbox.php". Use the source code below...

 

chatbox.php

<!DOCTYPE html>
 
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> //access jquery
<style>
#chatBoxContainer {
height: 500px;
width: 500px;
padding-top: 1%;
box-shadow: 5px 5px 10px #000;
background: #ccc;
}
#chatBox {
height: 90%;
width: 95%;
margin-left: 2.5%;
background: #f7f7f7;
}
#chatMessage {
height: auto;
width: 95%;
margin-left: 2.5%;
}
#userBox {
height: auto;
width: 95%;
margin-left: 2.5%;
margin-top: 10px;
}
textarea {
height: 16px;
width: 87.5%;
resize: none;
}
input {
float: right;
}
</style>
<script>
//this runs the fetch_chat function every 3 seconds to check for new messages
$(document).ready(function(){
setInterval(fetch_chat, 3000);
});

//this function fetches messages from the database and echos them into the chat box if there are new ones
function fetch_chat(){
var hr = new XMLHttpRequest();
var url = "fetch_chat.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
var text = hr.responseText;
$('chatBox').html(text);
}
}
hr.send();
}

//this submits chat messages sent by the user
function submit_chat(){
var message = $('textarea').val();
var hr = new XMLHttpRequest();
var url = "fetch_chat.php";
var data = "message="+message+"&submit_chat=Submit";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
var text = hr.responseText;
if(text == 0){
alert('There was an error submitting the message!');
} else {
var content = $('#chatBox').html();
$('#chatBox').html(content+text);
}
}
}
hr.send(data);
}

</script>
</head>
<body>
<div id='chatBoxContainer'>
<div id='chatBox'>
 
</div>
<div id='userBox'>
<textarea></textarea>
<input type='submit' value='Enter' onClick="submit_chat()"> //when this button is clicked the "submit_chat()" function is fired
</div>
</div>
</body>
</html>

Now that you have that file in place you need to create the php parser for submitting the chat messages. See below.

 

submit_chat.php

<?php
 
$time = date("Y-m-d H:i:s"); //this var equals the current time
 
if(isset($_POST['submit_chat'])){ //ensure that a request was sent before running the code
$message = $_POST['message']; //this variable holds the message data sent by the user
 
$sql = "INSERT INTO chat (message, time_sent) VALUES ('$message', '$time')"; //variable holding our sql command
$query = mysqli_query($conn, $sql); //initiate the query and specify both the connection and the command
if(!$query){ //check for errors
echo "0";
} else {
echo "<div id='chatMessage'>$message</div>"; //echo the message back to the main page
}
}
 
?>

Good job. Next you need to create the php file that will check for new messages.

 

fetch_chat.php

<?php
 
$sql = "SELECT * FROM chat"; //command
$query = mysqli_query($conn, $sql); //initiate query
while($row = mysqli_fetch_array($query)){ //run a while loop that fetches an array from the database
$message = $row['message']; //message data
$time_sent = $row['time_sent']; //the time that the message was sent
 
echo "<div id='chatMessage'>$message</div>"; //echo the message back to the main file for displaying
}

//Keep in mind that this while loop will run for every message in the database and send them all back to the main file via the ajax request

?>

Excellent. Now try it out and see how it works. Let me know if you find any bugs. You can modify the css and whatever else you like to fit your own needs. Enjoy!

Edited by KenBrace
Link to comment
Share on other sites

I spent over an hour getting all that together so I haven't really tested it properly since I'm a bit worn out. So for anyone who has some extra free time, I would appreciate if you could run some tests and report any bugs you find. 

Edited by KenBrace
Link to comment
Share on other sites

 

Maybe show the connection file used.  I don't show it in your code or any include config file.

mysqli_query($conn, $sql);

 

Good idea. The config file you should use for this tutorial is given below.

 

config.php

<?php
 
$host = "your host name here (usually localhost)";
$user = "your mysql username here";
$password  = "the password for the mysql user given above";
$db = "name of your databse";
 
$conn = mysqli_connect($host, $user, $password, $db); //connect to the database using the login information given in the variables above.
if(!$conn){ //check for connection errors
echo "There was an error connecting to the database!";
}
 
?>

You should include this config file at the top of submit_chat.php and fetch_chat.php using the following line of code at the top of the pages.

include_once("config.php");

Also keep in mind that you should close the connections in the two files at the bottom of the files. You can do this with the following code.

mysqli_close($conn);
Edited by KenBrace
Link to comment
Share on other sites

Tried it out, but receiving an error:

http://digitizedesign.com/examples/live-chat/chatbox.php

 

My bad. The first problem is that I used php comments in an HTML document. Would you mind editing the posts and changing the "//(comment)" to "<!-- (comment) -->" for both cases?

 

I'll look into the second. Give me a minute.

 

EDIT: I found the issue. The problem is that in the "submit_chat()" function the var "url" gives the wrong address. It should say "submit_chat.php" instead or "fetch_chat.php".

Edited by KenBrace
Link to comment
Share on other sites

I updated it, appears on refresh it doesn't pull in the old chats tho.  Also to be real useful would be nice to have users tied to it, but that's another project I'm sure.

 

I did a bit of work, cleaned up the code, tested it, etc. and offered the download package in another thread. If you have the time maybe upload the new files and see how it works. I included a name along with each post. However right now it is limited to "Guest" since it isn't linked to the system's user base.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...