
|
49 Projects
|
||||||||||
|
AsteroidsBlackjackBrowsergameChatCoinflipCryptFirst Person ShooterForumHangmanLightboxLogin SystemMath QuizMemoryObject Mouse EvadorPapiJumpPokerQuizRich Text Editor WYSIWYGSnakeSystem ExplorerThe Impossible QuizTic Tac Toe CalculatorCalendarClockColor PickerCustom MessageboxDictionaryImage EditorImage GeneratorImage SlideshowLink ActivationMessage SystemNewsletterNumber ConverterOnline KeyboardPaginationPoker Chance CalculatorProgress BarReaction TimerRSS FeedSearch EngineStarRatingStopwatchSyntax HighlighterText ReplacerURL ShortenerUser Management SystemVisitor Counter
|
||||||||||
Introduction Alot of populair websites have a online chat feature, and I thought, I can also create that! I kept it as simple as possible, but you can ofcourse make it as complicated as you want. My code only has the ability to send plain text, but you can extend it with for example smilies, images, bbcode, buzz, an avatar etc. In this chat program, everyone can join and enter the name they want in the chat (if that username is not already taken). The chat uses the following resources: The project consists out of 3 files: message.php (which retrieves and sends messages), chat_functions.js (which interacts between message.php and chat.html) and chat.html (which contains the HTML form). Interface The interface of my chat will be around 400px height and 500 px width, and will have the following items:
Database The MySQL-tables: CREATE TABLE messages ( mes_id INT(11) AUTO_INCREMENT, mes_text CHAR(255) NOT NULL, username CHAR(255) NOT NULL, PRIMARY KEY (mes_id) ) CREATE TABLE active_users ( user_id INT(11) AUTO_INCREMENT NOT NULL, username CHAR(255) UNIQUE NOT NULL, PRIMARY KEY (user_id) ) Programming Part one: message.phpThis part of our project sends and retrieves messages using our database. First off, starting the session and connecting to the database: Code Snippet (Syntax highlighted) - Toggle Wrap <?php /* Starting session */ session_start(); // // DATABASECONNECTION // $dbuser = "root"; // Change this into your own user $dbpassword = ""; // Change this into your own password $database = "main"; // Change this into your own database name $dbhost = "localhost"; // Change this into your own host (but mostly, localhost is used) $dbconnection = mysql_connect($dbhost,$dbuser,$dbpassword) or die("Couldn't connect to server"); $db = mysql_select_db($database,$dbconnection) or die("Couldn't select database"); Then retrieving what action needs to be undertaken: add_mes - Add an message get_mes - Retrieve the messages in the database get_users - Retrieve the users active in the chatroom add_user - Add a user to the active users in the chatroom rem_user - Remove a user from the active users in the chatroom Code Snippet (Syntax highlighted) - Toggle Wrap /* Retrieving the action */ if (isset($_GET['act'])) { $action = htmlentities(addslashes($_GET['act'])); } else { $action = "none"; } Taking action, switching the $action. See above for explaination of the cases. Code Snippet (Syntax highlighted) - Toggle Wrap switch ($action) { case "get_mes" : /* If a chat username exists, return the latest 15 messages */ if (isset($_SESSION['chat_username'])) { /* Retrieving the messages out of the database */ $query = "SELECT * FROM messages ORDER BY mes_id DESC LIMIT 15"; $result = mysql_query($query) or die("Could not retrieve messages."); /* Echoing the messages */ while ($row = mysql_fetch_array($result)) { echo $row['username'].": ".$row['mes_text']."<br />"; } } break; case "add_mes" : /* If a message is given in the URL, and a chat username exsists, add a message to the database */ if (isset($_GET['mes']) && isset($_SESSION['chat_username'])) { /* Cleaning the message from bad data: */ $message = htmlentities(addslashes($_GET['mes'])); /* Inserting the message into the database */ $query = "INSERT INTO messages (username, mes_text) VALUES ('".$_SESSION['chat_username']."', '".$message."')"; $result = mysql_query($query) or die("Could not send message."); echo "Message sent."; } else { echo "No message was given."; } break; case "get_users" : /* If a username is set, retrieve and echo all users */ if (isset($_SESSION['chat_username'])) { /* Retrieving users out of database */ $query = "SELECT * FROM active_users ORDER BY username DESC"; $result = mysql_query($query) or die("Could not retrieve users."); /* Echoing the users */ while ($row = mysql_fetch_array($result)) { echo $row['username']."<br />"; } } break; case "add_user" : /* If no username already exists, and a username is given in the URL, add it to the active users */ if (!isset($_SESSION['chat_username']) && isset($_GET['username'])) { /* Inserting the username into the database */ $query = "INSERT INTO active_users (username) VALUES ('".htmlentities(addslashes($_GET['username']))."')"; $result = mysql_query($query) or die("Could not add user."); /* Adding the username into the session variable */ $_SESSION['chat_username'] = htmlentities(addslashes($_GET['username'])); echo "User added."; } break; case "rem_user" : /* If a chat username already exists, remove it */ if (isset($_SESSION['chat_username'])) { /* Removing username from database */ $query = "DELETE FROM active_users WHERE username='".$_SESSION['chat_username']."'"; $result = mysql_query($query) or die("Could not remove user."); /* Removing username from the session */ unset($_SESSION['chat_username']); echo "User removed."; } break; default : echo "Invalid action."; break; } ?> Part two: chat_functions.jsThis part of our project interacts between message.php and the interface. The first function, RetrieveMessages(), sends a AJAX request to message.php with the action get_mes. Message.php then returns the messages. RetrieveMessages() then updates the innerHTML of the chat window. Read the comments: Code Snippet (Syntax highlighted) - Toggle Wrap /* * This function retrieves the messages and displays them in the chat_messages div */ function RetrieveMessages() { var ajax = false; // Create the object: // Choose the objecttype, depending on what is supported: if (window.XMLHttpRequest) { // IE 7, Mozilla, Safari, Firefox, Opera, most browsers: ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Old IE-browsers // Make the type Msxml2.XMLHTTP, if possible: try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { // Else use the other type: try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { } } } // Retrieving the data from the page if (ajax) { /* Creating url */ var url = "message.php?act=get_mes"; ajax.open('GET', url); // Sends request ajax.send(null); // Function that handles response ajax.onreadystatechange=function(){ // If everything is OK: if ( (ajax.readyState == 4) && (ajax.status == 200) ) { // Returns the value to the document document.getElementById('chat_messages').innerHTML = ajax.responseText; } } } else { // AJAX is not useable alert('It is not possible to connect, please update your browser.'); } } The second function, RetrieveUsers(), sends a AJAX request to message.php with the action get_users. Message.php then returns the active users. RetrieveMessages() then updates the innerHTML of the active users div. Read the comments: Code Snippet (Syntax highlighted) - Toggle Wrap /* * This function retrieves the users and displays them in the user_online div */ function RetrieveUsers() { var ajax = false; // Create the object: // Choose the objecttype, depending on what is supported: if (window.XMLHttpRequest) { // IE 7, Mozilla, Safari, Firefox, Opera, most browsers: ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Old IE-browsers // Make the type Msxml2.XMLHTTP, if possible: try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { // Else use the other type: try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { } } } // Retrieving the data from the page if (ajax) { var url = "message.php?act=get_users"; ajax.open('GET', url); // Sends request ajax.send(null); // Function that handles response ajax.onreadystatechange=function(){ // If everything is OK: if ( (ajax.readyState == 4) && (ajax.status == 200) ) { // Returns the value to the document document.getElementById('users_online').innerHTML = ajax.responseText; } } } else { // AJAX is not useable alert('It is not possible to connect, please update your browser.'); } } The third function, SendMessage(), retrieves the message value, sends a AJAX request to message.php with the action add_mes. Message.php then adds the message to the database. Code Snippet (Syntax highlighted) - Toggle Wrap /* * This function retrieves the value out of the textbox, then empties the textbox and sends the message */ function SendMessage() { var ajax = false; // Create the object: // Choose the objecttype, depending on what is supported: if (window.XMLHttpRequest) { // IE 7, Mozilla, Safari, Firefox, Opera, most browsers: ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Old IE-browsers // Make the type Msxml2.XMLHTTP, if possible: try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { // Else use the other type: try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { } } } // Retrieving the data from the page if (ajax) { /* Retrieving the message and emptying the message_txt textbox */ var message = document.getElementById('message_txt').value; document.getElementById('message_txt').value = ""; var url = "message.php?act=add_mes&mes=" + encodeURIComponent(message); ajax.open('GET', url); // Sends request ajax.send(null); // Function that handles response ajax.onreadystatechange=function(){ // If everything is OK: if ( (ajax.readyState == 4) && (ajax.status == 200) ) { // Does nothing... } } } else { // AJAX is not useable alert('It is not possible to connect, please update your browser.'); } } The fourth function, AddUser(), asks the visitor for a username, sends a AJAX request to message.php with the action add_user. Message.php then adds the user to the database. Code Snippet (Syntax highlighted) - Toggle Wrap /* * This function prompts the visitor for a username and then send that username */ function AddUser() { var ajax = false; // Create the object: // Choose the objecttype, depending on what is supported: if (window.XMLHttpRequest) { // IE 7, Mozilla, Safari, Firefox, Opera, most browsers: ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Old IE-browsers // Make the type Msxml2.XMLHTTP, if possible: try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { // Else use the other type: try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { } } } // Retrieving the data from the page if (ajax) { /* Retrieving the message and emptying the message_txt textbox */ var username = prompt("Enter a username to use in the chat:"); var url = "message.php?act=add_user&username=" + encodeURIComponent(username); if (username != null) { ajax.open('GET', url); // Sends request ajax.send(null); // Function that handles response ajax.onreadystatechange=function(){ // If everything is OK: if ( (ajax.readyState == 4) && (ajax.status == 200) ) { if (ajax.responseText != "User added.") { AddUser(); } else { document.getElementById('join_chat').style.display = "none"; } } } } else { document.getElementById('join_chat').style.display = "inline"; alert("You pressed cancel and refused to join the chat."); } } else { // AJAX is not useable alert('It is not possible to connect, please update your browser.'); } } The fifth function, RemUser(), sends a AJAX request to message.php with the action rem_user. Message.php then removes the user from the database. Code Snippet (Syntax highlighted) - Toggle Wrap /* * This function removes the online user */ function RemUser() { var ajax = false; // Create the object: // Choose the objecttype, depending on what is supported: if (window.XMLHttpRequest) { // IE 7, Mozilla, Safari, Firefox, Opera, most browsers: ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Old IE-browsers // Make the type Msxml2.XMLHTTP, if possible: try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { // Else use the other type: try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { } } } // Retrieving the data from the page if (ajax) { /* Retrieving the message and emptying the message_txt textbox */ var message = document.getElementById('message_txt').value; document.getElementById('message_txt').value = ""; var url = "message.php?act=rem_user"; ajax.open('GET', url); // Sends request ajax.send(null); // Function that handles response ajax.onreadystatechange=function(){ // If everything is OK: if ( (ajax.readyState == 4) && (ajax.status == 200) ) { // Does nothing... } } } else { // AJAX is not useable alert('It is not possible to connect, please update your browser.'); } } Now setting the window events. Retrieving messages onload and every second. When the user leaves the page, remove him from the active users list. Code Snippet (Syntax highlighted) - Toggle Wrap /* When the user joins, retrieve the active messages and users */ window.onload=function(){ RetrieveMessages(); RetrieveUsers(); AddUser(); /* Set an interval when the chat is refreshed. */ setInterval(function(){ RetrieveMessages(); RetrieveUsers(); }, 1000); } window.onunload=function(){ RemUser(); } Part three: chat.htmlThis is the interface of the chat, and is pretty straight-forward what it does and I really don't feel like writing more. Code Snippet (Syntax highlighted) - Toggle Wrap <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Chat</title> <script type="text/javascript" src='chat_functions.js'></script> </head> <body> <!-- /* =============== === License === Copyright (C) 2010 Graphix of WebDevProject.com Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". Created by Graphix of WebDevProject.com Visit us at: http://www.webdevproject.com/ Contact: http://www.webdevproject.com/ Or you can PM at DaniWeb (username: Graphix) === License === =============== */ //--> <div style='position:relative; top:0px; left:0px; width:600px; height:400px; border:1px solid rgb(127,157,185); background-color:rgb(250,250,255); font-family:Arial; font-size:13px;'> <div id='join_chat' style='position:absolute; top:10px; left:530px; font-weight:bold; color:#6CA6CD; display:none;'><a style='color:#6CA6CD; text-decoration:none;' href='#' onclick='AddUser(); return false;'>Join chat</a></div> <div style='position:absolute; top:10px; left:10px; font-weight:bold; color:#6CA6CD;'>Users:</div> <div style='position:absolute; top:10px; left:140px; font-weight:bold; color:#6CA6CD;'>Messages:</div> <div style='position:absolute; top:28px; left:10px; width:110px; border:1px solid rgb(127,157,185); height:352px; background-color:#FFF; padding:5px;' id='users_online'>users</div> <div style='position:absolute; top:28px; left:140px; border:1px solid rgb(127,157,185); width:440px; height:262px; background-color:#FFF; padding:5px;' id='chat_messages'>chat</div> <textarea id='message_txt' style=' position:absolute; top:309px; left:140px; width:350px; padding:0px; height:78px; border:1px solid rgb(127,157,185); font-family:Arial; font-size:13px; background-color:#FFF;'></textarea> <input type='button' value='Send' onclick='SendMessage();' style='position:absolute; top:310px; left:500px; width:90px; height:82px; font-size:24px; font-family:Arial;' /> </div> </body> </html> Using this code Don't forget to create the tables and to change the database connection details! You can download the source code using the following link: http://www.webdevproject.com/zips/Chat-sourcecode.zip I tested out the code, and it works in all major browsers (IE, FF, Opera, Google Chrome, and all other NetScape clones). If the code does not work, post a comment below with the problem and I will help you and fix the code. Comments
New project: Math Quiz
2010-11-09 18:07:48 Read more... New project: Custom Messagebox 2010-11-06 19:10:50 Read more... New project: Visitor Counter 2010-11-01 21:39:04 Read more... New project: Image Editor 2010-11-01 21:37:27 Read more... New project: Image Generator 2010-11-01 21:33:05 Read more... |