PHP implements the simplest chat room Application
Introduction
Chat applications are very common online. Developers also have many choices when building such applications. This article describes how to implement a PHP-AJAX-based chat application that can send and receive messages without refreshing the page.
Core Logic
Before defining the core functions of an application, let's take a look at the basic appearance of the chat application, as shown below:
Enter the chat text in the text box at the bottom of the chat window. Click the Send button to start executing the set_chat_msg function. This is an Ajax-based function, so you can send chat text to the server without refreshing the page. The program runs chat_send_ajax.php and the user name and chat text on the server.
- //
- // Set Chat Message
- //
-
- function set_chat_msg()
- {
- if(typeof XMLHttpRequest != "undefined")
- {
- oxmlHttpSend = new XMLHttpRequest();
- }
- else if (window.ActiveXObject)
- {
- oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
- }
- if(oxmlHttpSend == null)
- {
- alert("Browser does not support XML Http Request");
- return;
- }
-
- var url = "chat_send_ajax.php";
- var strname="noname";
- var strmsg="";
- if (document.getElementById("txtname") != null)
- {
- strname = document.getElementById("txtname").value;
- document.getElementById("txtname").readOnly=true;
- }
- if (document.getElementById("txtmsg") != null)
- {
- strmsg = document.getElementById("txtmsg").value;
- document.getElementById("txtmsg").value = "";
- }
-
- url += "?name=" + strname + "&msg=" + strmsg;
- oxmlHttpSend.open("GET",url,true);
- oxmlHttpSend.send(null);
- }
The PHP module receives form data from the Query String and updates it to the database table named "chat. The chat database table is namedID
,USERNAME
,CHATDATE
AndMSG
. The ID field is auto-incrementing, so the value assignment of this ID field is auto-incrementing. The current date and time are updated to the CHATDATE column.
- require_once('dbconnect.php');
-
- db_connect();
-
- $msg = $_GET["msg"];
- $dt = date("Y-m-d H:i:s");
- $user = $_GET["name"];
-
- $sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " .
- "values(" . quote($user) . "," .
- quote($dt) . "," . quote($msg) . ");";
-
- echo $sql;
-
- $result = mysql_query($sql);
- if(!$result)
- {
- throw new Exception('Query failed: ' . mysql_error());
- exit();
- }
To receive chat messages from all users in the database table, the timer function is set to call the following JavaScript commands in a 5-second cycle, that is, the get_chat_msg function is executed every 5 seconds.
Var t = setInterval (function () {get_chat_msg ()}, 5000 );
Get_chat_msg is an Ajax-based function. It executes the chat_recv_ajax.php program to obtain chat information from the database table. In the onreadystatechange attribute, another JavaScript function get_chat_msg_result is connected. When a chat message from a database table is returned, the program control enters the get_chat_msg_result function.
- //
- // General Ajax Call
- //
-
- var oxmlHttp;
- var oxmlHttpSend;
-
- function get_chat_msg()
- {
- if(typeof XMLHttpRequest != "undefined")
- {
- oxmlHttp = new XMLHttpRequest();
- }
- else if (window.ActiveXObject)
- {
- oxmlHttp = new ActiveXObject("Microsoft.XMLHttp");
- }
- if(oxmlHttp == null)
- {
- alert("Browser does not support XML Http Request");
- return;
- }
-
- oxmlHttp.onreadystatechange = get_chat_msg_result;
- oxmlHttp.open("GET","chat_recv_ajax.php",true);
- oxmlHttp.send(null);
- }
In the chat_recv_ajax.php programselect
Command to collect. To limit the number of rows, the limit clause limit 200 is also provided in the SQL query, that is, the last 200 rows in the chat database table are required. The obtained message is returned to the Ajax function, which is used to display the content in the chat window.
- Require_once ('dbconnect. php ');
-
- Db_connect ();
-
- $ SQL = "SELECT *, date_format (chatdate, '% d-% m-% Y % R ')
- As cdt from chat order by ID desc limit 200 ";
- $ SQL = "SELECT * FROM (". $ SQL. ") as ch order by ID ";
- $ Result = mysql_query ($ SQL) or die ('query failed: '. mysql_error ());
-
- // Update Row Information
- $ Msg = "";
- While ($ line = mysql_fetch_array ($ result, MYSQL_ASSOC ))
- {
- $ Msg = $ msg ."".
- "".
- "";
- }
- $ Msg = $ msg. "<table style =" color: blue; font-family: verdana, arial ;".
- "Font-size: 10pt;" border = "0">
- <Tbody> <tr> <td> ". $ line [" cdt "].
- "</Td> <td>". $ line ["username"].
- ": </Td> <td>". $ line ["msg"].
- "</Td> </tr> </tbody> </table> ";
-
- Echo $ msg;
-
- When data is ready, JavaScript Functions collect data received by PHP. The data will be placed in the DIV label. OxmlHttp. responseText retains the chat messages received from the PHP program and copies them to the document. getElementById ("DIV_CHAT"). innerHTML attribute of the DIV tag.
-
- Function get_chat_msg_result (t)
- {
- If (oxmlHttp. readyState = 4 | oxmlHttp. readyState = "complete ")
- {
- If (document. getElementById ("DIV_CHAT ")! = Null)
- {
- Document. getElementById ("DIV_CHAT"). innerHTML = oxmlHttp. responseText;
- OxmlHttp = null;
- }
- Var scrollDiv = document. getElementById ("DIV_CHAT ");
- ScrollDiv. scrollTop = scrollDiv. scrollHeight;
- }
- }
The following SQL CREATE TABLE command can be used to CREATE a database TABLE named chat. All information entered by the user will go to the database table.
Create table chat (id bigint AUTO_INCREMENT, username varchar (20 ),
Chatdate datetime, msg varchar (500), primary key (id ));
Point of interest
The code used to implement the chat application is very interesting. It can be improved into a completely mature HTTP chat application. The logic for creating this application is also very simple. Even beginners do not have any difficulties.
License
This article, as well as any related source Code and files, is licensed by The Code Project Open License (CPOL.
Http://www.codeceo.com/article/php-chart-app.html.
Chat Application in PHP