Introduced
Chat applications are very common on the web. Developers also have a lot of choices in building this type of application. This article describes how to implement a Php-ajax chat application and can send and receive messages without having to refresh the page.
Core Logic
Before defining the core functionality of your application, take a look at the basic look of the chat application, as shown in the screenshot below:
Enter the chat text through the input box at the bottom of the chat window. Click the Send button to start the function set_chat_msg. This is an AJAX based function, so you can send chat text to the server without refreshing the page. The program executes chat_send_ajax.php and user name and chat text in 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, which is updated to the database table named Chat. The Chat database table has ID
columns named, USERNAME
,, CHATDATE
and MSG
. The ID field is an automatically incremented field, so the assignment of this ID field is incremented automatically. 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 loop 5 seconds to invoke the following JavaScript command, which is to perform the get_chat_msg function 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 property, another JavaScript function get_chat_msg_result is connected. Program control enters the Get_chat_msg_result function while returning the chat message from the database table.
- //
- 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 program, chat messages from users are collected through SQL select
commands. To limit the number of rows, a restriction clause (limit 200) is also given in the SQL query, which requires the last 200 rows in the Chat database table. The received message is then returned to the AJAX function 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;
- As the data is ready, the JavaScript function collects the data from the PHP received. The data will be placed inside the div tag. Oxmlhttp.responsetext will retain the chat message received from the PHP program and copy it to the document.getElementById ("Div_chat") of the DIV tag. innerHTML properties.
- 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 is entered into the database table.
CREATE TABLE Chat (id bigint auto_increment,username varchar (20),
chatdate datetime,msg varchar (), primary key (ID));
Points of interest
This code for implementing the chat application is very interesting. It can be improved into a fully fledged HTTP chat application. The logic for creating the application is also very simple. Even beginners will not have any difficulty understanding it.
License
This article, along with any related source code and files, is licensed by the Code Project Open License (Cpol).
Translation Links: http://www.codeceo.com/article/php-chart-app.html
English Original: Chat application in PHP
"Responsible Editor: Wangxueyan TEL: (010) 68476606"