Chat applications are very common online, and developers also have a lot of choices when building such applications. This article introduces how to implement a chat application based on PHP-AJAX, and you 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 Query String and updates it to the database table named chat. The chat database table has columns named ID, USERNAME, CHATDATE, and MSG. 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 program, user-dependent chat messages are collected using the SQL select command. 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."
". $ Line [" cdt "]." |
". $ Line [" username "].": |
". $ Line [" msg "]." |
"; 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 ));
The code used to implement the chat application is very interesting. it can be improved into a completely mature HTTP chat application, and the logic for creating the application is also very simple, even beginners do not have any difficulties in understanding it. I hope this article will be helpful to everyone's learning.