Home Backend Development PHP Tutorial Ajax PHP JavaScript MySQL implements a simple refresh-free online chat room

Ajax PHP JavaScript MySQL implements a simple refresh-free online chat room

May 02, 2018 am 10:51 AM
ajax javascript mysql

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>消息显示区</h3>
<p id="up">
</p>
<hr />
Copy after login

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>发言栏</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>
Copy after login

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(&#39;var data = &#39;+ajax.responseText);
      // 遍历data数组,把内部的信息一个个的显示到页面上
      var s = "";
      for(var i = 0 ; i < data.length;i++){
        data[i];
        s += "("+data[i].add_time+") >>>";
        s += "<p style=&#39;color:"+data[i].color+";&#39;>";  
        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(&#39;get&#39;,&#39;./chatroom.php&#39;);
  ajax.send(null);  

}

// 更新信息的执行时机
window.onload = function(){
  //showmessage();  
  // 制作轮询,实现自动的页面更新
  setInterval("showmessage()",3000);
}
</script>
Copy after login


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(&#39;form&#39;)[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(&#39;post&#39;,&#39;./chatroom_insert.php&#39;);
    xhr.send(formdata);
    document.getElementById("msg").value="";
    //return false;
  }

  // 2秒后实现提示信息的消失
  function hideresult(){
    document.getElementById(&#39;result&#39;).innerHTML = "";  
  }
</script>
Copy after login

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(&#39;var data = &#39;+ajax.responseText);
      // 遍历data数组,把内部的信息一个个的显示到页面上
      var s = "";
      for(var i = 0 ; i < data.length;i++){
        data[i];
        s += "("+data[i].add_time+") >>>";
        s += "<p style=&#39;color:"+data[i].color+";&#39;>";  
        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(&#39;get&#39;,&#39;./chatroom.php?maxId=&#39;+maxId);
  ajax.send(null);  

}

// 更新信息的执行时机
window.onload = function(){
  //showmessage();  
  // 制作轮询,实现自动的页面更新
  setInterval("showmessage()",3000);
}
</script>
Copy after login


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>
Copy after login

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;
Copy after login

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(&#39;var data = &#39;+ajax.responseText);
      // 遍历data数组,把内部的信息一个个的显示到页面上
      var s = "";
      for(var i = 0 ; i < data.length;i++){
        data[i];
        s += "("+data[i].add_time+") >>>";
        s += "<p style=&#39;color:"+data[i].color+";&#39;>";  
        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(&#39;get&#39;,&#39;./chatroom.php?maxId=&#39;+maxId);
  ajax.send(null);  

}

// 更新信息的执行时机
window.onload = function(){
  //showmessage();  
  // 制作轮询,实现自动的页面更新
  setInterval("showmessage()",3000);
}
</script>




消息显示区


发言栏

颜色 表情 聊天对象

<script> function send(){ // 向服务器差入相关的数据 var form = document.getElementsByTagName(&#39;form&#39;)[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(&#39;post&#39;,&#39;./chatroom_insert.php&#39;); xhr.send(formdata); document.getElementById("msg").value=""; //return false; } // 2秒后实现提示信息的消失 function hideresult(){ document.getElementById(&#39;result&#39;).innerHTML = ""; } </script> 发言:

Copy after login


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)
Copy after login

Server-side code

<?php

// 获得最新的聊天信息
$conn = mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;mysql&#39;);
mysql_select_db(&#39;test&#39;);
mysql_query(&#39;set names utf8&#39;);

$maxId = $_GET[&#39;maxId&#39;];

// 防止获取重复数据,本次请求的记录结果id要大鱼上次获得的id
$sql = "select * from message where id >"."&#39;$maxId&#39;";
$qry = mysql_query($sql);

$info = array();
while($rst = mysql_fetch_assoc($qry)){
  $info[] = $rst;
}


// 通过json格式给客户端提供数据
echo json_encode($info);


?>
Copy after login


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.

•The interface is poorly made and there is no beautification effect. The effect should be great after adding Bootstrap.

•The mobile phone adaptation effect is not good, and the color control cannot be displayed normally on Windows Phone.

Related recommendations:

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles