KenBrace Posted February 20, 2015 Share Posted February 20, 2015 (edited) 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 February 20, 2015 by KenBrace Nathan and Coolprogramer36 2 Quote Link to comment Share on other sites More sharing options...
KenBrace Posted February 20, 2015 Author Share Posted February 20, 2015 (edited) 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 February 20, 2015 by KenBrace Quote Link to comment Share on other sites More sharing options...
Administrators Nathan Posted February 20, 2015 Administrators Share Posted February 20, 2015 Maybe show the connection file used. I don't show it in your code or any include config file. mysqli_query($conn, $sql); KenBrace 1 Quote Link to comment Share on other sites More sharing options...
Lizel Posted February 21, 2015 Share Posted February 21, 2015 Thanks for posting this, helpful ! Quote Link to comment Share on other sites More sharing options...
KenBrace Posted February 22, 2015 Author Share Posted February 22, 2015 (edited) 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 February 22, 2015 by KenBrace Quote Link to comment Share on other sites More sharing options...
Administrators Nathan Posted February 23, 2015 Administrators Share Posted February 23, 2015 Tried it out, but receiving an error: http://digitizedesign.com/examples/live-chat/chatbox.php Quote Link to comment Share on other sites More sharing options...
KenBrace Posted February 23, 2015 Author Share Posted February 23, 2015 (edited) 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 February 23, 2015 by KenBrace Quote Link to comment Share on other sites More sharing options...
KenBrace Posted February 23, 2015 Author Share Posted February 23, 2015 It might also be a good idea to run mysqli_real_escape_string() on the $message variable in "submit_chat.php" to protect from mysql injection. Quote Link to comment Share on other sites More sharing options...
AtlantaSports Posted February 24, 2015 Share Posted February 24, 2015 I am still getting an error whenever it comes up. Quote Link to comment Share on other sites More sharing options...
KenBrace Posted February 24, 2015 Author Share Posted February 24, 2015 I am still getting an error whenever it comes up. That's because the code errors I mentioned haven't been fixed yet. I'll start a new thread with the completed version and offer a download for anyone who wants all the files. Quote Link to comment Share on other sites More sharing options...
Administrators Nathan Posted February 25, 2015 Administrators Share Posted February 25, 2015 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. Quote Link to comment Share on other sites More sharing options...
KenBrace Posted February 26, 2015 Author Share Posted February 26, 2015 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.