


Ajax PHP JavaScript MySQL implements a simple refresh-free online chat room
This article mainly introduces Ajax PHP JavaScript MySQL to implement a simple non-refresh online chat room, which has certain reference value. Interested friends can refer to it
for better use of these two days I learned the relevant knowledge of Ajax and made a simple online chat room.
Ideas
To implement a chat room, it is basically to pass data through Ajax and let PHP realize the difference in data and search, and then hand it over to the front-end JavaScript to update the page to achieve the function of instant chat.
Message display area
The message display area is a p block. After we obtain the server-side information with the help of Ajax, we use JavaScript to update the page.
<h3 id="消息显示区">消息显示区</h3> <p id="up"> </p> <hr />
Send a message
The message module, to put it bluntly, is the process of inserting data into the server, which is also relatively simple.
<h3 id="发言栏">发言栏</h3> <p id="bottom"> <form action="./chatroom_insert.php"> <p id="chat_up"> <span>颜色</span> <input type="color" name="color"/> <span>表情</span> <select name="biaoqing"> <option value="微笑地">微笑地</option> <option value="猥琐地">猥琐地</option> <option value="和蔼地">和蔼地</option> <option value="目不转睛地">目不转睛地</option> <option value="傻傻地">傻傻地</option> </select> <span>聊天对象</span> <select name="receiver"> <option value="">所有的人</option> <option value="老郭">老郭</option> <option value="小郭">小郭</option> <option value="大郭">大郭</option> </select> </p> <p id="chat_bottom"> <textarea id="msg" name="msg" style="width:380px;height:auto;"></textarea> <input type="button" value="发言" onclick="send()" /> 发言:<span id="result"></span> </p> </form> </p>
Section
Let’s start using code to implement relevant business logic.
Message display
Our idea is that every once in a while, the client sends a request to the server and polls to obtain the latest data.
<script> function showmessage(){ var ajax = new XMLHttpRequest(); // 从服务器获取并处理数据 ajax.onreadystatechange = function(){ if(ajax.readyState==4) { //alert(ajax.responseText); // 将获取到的字符串转换成实体 eval('var data = '+ajax.responseText); // 遍历data数组,把内部的信息一个个的显示到页面上 var s = ""; for(var i = 0 ; i < data.length;i++){ data[i]; s += "("+data[i].add_time+") >>>"; s += "<p style='color:"+data[i].color+";'>"; s += data[i].sender +" 对 " + data[i].receiver +" "+ data[i].biaoqing+"说:" + data[i].msg; s += "</p>"; } // 开始向页面时追加信息 var showmessage = document.getElementById("up"); showmessage.innerHTML += s; } } ajax.open('get','./chatroom.php'); ajax.send(null); } // 更新信息的执行时机 window.onload = function(){ //showmessage(); // 制作轮询,实现自动的页面更新 setInterval("showmessage()",3000); } </script>
The more important thing is the use of the setInterval function to achieve interval triggering of request events.
Message sending
Regarding message sending, just send it to the server through a form. We use the latest technology of Html5 here, FormData. Generally speaking, the current mainstream modern browsers support this technology. Using FormData we can easily obtain the data of a form.
Note: FormData collects form data in the form of key-value pairs, so the corresponding form item must have a name attribute, otherwise the form will No data value could be collected for this item.
<script> function send(){ // 向服务器差入相关的数据 var form = document.getElementsByTagName('form')[0]; var formdata = new FormData(form); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState==4) { //alert(xhr.resposneText); document.getElementById("result").innerHTML = xhr.responseText; setTimeout("hideresult()",2000); } } xhr.open('post','./chatroom_insert.php'); xhr.send(formdata); document.getElementById("msg").value=""; //return false; } // 2秒后实现提示信息的消失 function hideresult(){ document.getElementById('result').innerHTML = ""; } </script>
It is worth pondering: the function implemented by the setTimeout function. After getting the feedback information from the server, it is updated in time behind the send button to give the user a good experience.
Optimization
After completing this, you can basically implement chat. However, the effect achieved will be very bad, mainly due to the following points.
•There is no scrolling display, you have to manually check the latest news every time.
•The data obtained contains a lot of duplicate data, which wastes traffic and makes it inconvenient to view information.
Display non-repetitive data
For displaying repetitive data, this is because we do not use the where statement, but it seems to be obtained every time All the data is gone. Just think about it, how can we get the latest data?
And different clients must be taken care of.
Hollywood Principle: Don’t come to me, I’ll come to you
This is also a lot of software A manifestation of the development philosophy is to let the customer decide what data to obtain, rather than beating the server to death with a stick. So we need to optimize the client in sending data requests.
<script> // 记录当前获取到的id的最大值,防止获取到重复的信息 var maxId = 0; function showmessage(){ var ajax = new XMLHttpRequest(); // 从服务器获取并处理数据 ajax.onreadystatechange = function(){ if(ajax.readyState==4) { //alert(ajax.responseText); // 将获取到的字符串转换成实体 eval('var data = '+ajax.responseText); // 遍历data数组,把内部的信息一个个的显示到页面上 var s = ""; for(var i = 0 ; i < data.length;i++){ data[i]; s += "("+data[i].add_time+") >>>"; s += "<p style='color:"+data[i].color+";'>"; s += data[i].sender +" 对 " + data[i].receiver +" "+ data[i].biaoqing+"说:" + data[i].msg; s += "</p>"; // 把已经获得的最大的记录id更新 maxId = data[i].id; } // 开始向页面时追加信息 var showmessage = document.getElementById("up"); showmessage.innerHTML += s; //showmessage.scrollTop 可以实现p底部最先展示 // pnode.scrollHeight而已获得p的高度包括滚动条的高度 showmessage.scrollTop = showmessage.scrollHeight-showmessage.style.height; } } ajax.open('get','./chatroom.php?maxId='+maxId); ajax.send(null); } // 更新信息的执行时机 window.onload = function(){ //showmessage(); // 制作轮询,实现自动的页面更新 setInterval("showmessage()",3000); } </script>
Optimizing the display
Optimizing the display interface is essential. No one can tolerate having to manually send a piece of data. View the latest news. So we need to set the p of the display area.
Add scroll bar
<style> #up { height:320px; width:100%; overflow:auto; } </style>
Display the latest news every time
To put it bluntly, the p at the bottom is always displayed first.
//showmessage.scrollTop 可以实现p底部最先展示 // pnode.scrollHeight而已获得p的高度包括滚动条的高度 showmessage.scrollTop = showmessage.scrollHeight-showmessage.style.height;
Complete code
Front-end code
Ajax 聊天室 <script> // 记录当前获取到的id的最大值,防止获取到重复的信息 var maxId = 0; function showmessage(){ var ajax = new XMLHttpRequest(); // 从服务器获取并处理数据 ajax.onreadystatechange = function(){ if(ajax.readyState==4) { //alert(ajax.responseText); // 将获取到的字符串转换成实体 eval('var data = '+ajax.responseText); // 遍历data数组,把内部的信息一个个的显示到页面上 var s = ""; for(var i = 0 ; i < data.length;i++){ data[i]; s += "("+data[i].add_time+") >>>"; s += "<p style='color:"+data[i].color+";'>"; s += data[i].sender +" 对 " + data[i].receiver +" "+ data[i].biaoqing+"说:" + data[i].msg; s += "</p>"; // 把已经获得的最大的记录id更新 maxId = data[i].id; } // 开始向页面时追加信息 var showmessage = document.getElementById("up"); showmessage.innerHTML += s; //showmessage.scrollTop 可以实现p底部最先展示 // pnode.scrollHeight而已获得p的高度包括滚动条的高度 showmessage.scrollTop = showmessage.scrollHeight-showmessage.style.height; } } ajax.open('get','./chatroom.php?maxId='+maxId); ajax.send(null); } // 更新信息的执行时机 window.onload = function(){ //showmessage(); // 制作轮询,实现自动的页面更新 setInterval("showmessage()",3000); } </script>
消息显示区
发言栏
Database table structure
mysql> desc message; +----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | int(100) | NO | PRI | NULL | auto_increment | | msg | varchar(255) | NO | | NULL | | | sender | varchar(30) | NO | | NULL | | | receiver | varchar(30) | NO | | NULL | | | color | varchar(10) | YES | | NULL | | | biaoqing | varchar(10) | YES | | NULL | | | add_time | datetime | YES | | NULL | | +----------+--------------+------+-----+---------+----------------+ 7 rows in set (0.00 sec)
Server-side code
<?php // 获得最新的聊天信息 $conn = mysql_connect('localhost','root','mysql'); mysql_select_db('test'); mysql_query('set names utf8'); $maxId = $_GET['maxId']; // 防止获取重复数据,本次请求的记录结果id要大鱼上次获得的id $sql = "select * from message where id >"."'$maxId'"; $qry = mysql_query($sql); $info = array(); while($rst = mysql_fetch_assoc($qry)){ $info[] = $rst; } // 通过json格式给客户端提供数据 echo json_encode($info); ?>
Summary and outlook
##Summary
This is the complete example. To review, today’s gains are: •How to poll to obtain data, with the help of the setInterval function
•The data that disappears at regular intervals, with the help of the setTimeout function
•How to obtain the latest data: the client controls the sending The maxId parameter.
•How to optimize the display: overflow achieves scrolling effect; pnode.scrollTop controls the display bottom special effects
Outlook •Maybe you will find , the client sender is fixed, that’s because we don’t do user login. If the user logs in, our sender can be dynamically obtained from the Session. This can also be more consistent with people's subjective feelings.
php webSoket implementation chat room sample code (source code attached)
Detailed example of how to implement a chatbot using Python Slack API
#
The above is the detailed content of Ajax PHP JavaScript MySQL implements a simple refresh-free online chat room. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.