Ajax PHP JavaScript MySQL implementation simple no refresh online chat room _php instance

Source: Internet
Author: User
Tags eval setinterval ajax chat

To better use the relevant knowledge of Ajax learned in these two days, I made a simple online chat room.

Ideas

The realization chat room, basically is through the Ajax to pass the data, lets the PHP to realize to the data the difference enters and the search, then gives the front-end JavaScript to implement the page the renewal, achieves the instant chat function.

Message display Area

The message display area is a div block, and we use AJAX to get the server-side information to update the page with JavaScript.

 
 

Send a message

Message module, in fact, is the process of inserting data into the server, is also a relatively simple.

 

Plate

The following starts with code to implement the relevant business logic.

Message display

Our idea is that every once in a while, the client sends a request to the server and polls for the latest data.

 <script> function ShowMessage () {var ajax = new XMLHttpRequest (); 
      Fetch and process data Ajax.onreadystatechange = function () {if (ajax.readystate==4) {//alert (Ajax.responsetext) from the server;
      Converts the acquired string to entity eval (' var data = ' +ajax.responsetext);
      Traversal of the data array, the internal information is displayed to the page of 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+ "said:" + data[i].msg;

      S + + "</p>";
      ///Start appending information to page var showmessage = document.getElementById ("Up");

    showmessage.innerhtml = s;
  } ajax.open (' Get ', './chatroom.php ');  

Ajax.send (NULL);  
  }//Update the timing of the information window.onload = function () {//showmessage ();
Make polling, realize automatic page update setinterval ("ShowMessage ()", 3000); } </script> 

What is more important inside is the use of the SetInterval function to implement the interval trigger request event.

Message sending

For message sending, it can be sent to the server by Form. We use a state-of-the-art technology for the current HTML5, FormData, which is generally supported by the current mainstream modern browsers. Using Formdata, we can easily get the data for a form.

Note: Formdata collects form data in the form of key-value pairs, so the corresponding table item must have a Name property, otherwise the form will not collect data values for that item.

 <script>
  function Send () {
    //to server in relation to data
    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 ()");
      }
    Xhr.open (' Post ', './chatroom_insert.php ');
    Xhr.send (formdata);
    document.getElementById ("msg"). value= "";
    return false;
  }

  2 seconds to implement the vanishing
  function Hideresult () {
    document.getElementById (' result '). InnerHTML = "";
</script>

What is worth pondering is: the function that settimeout function realizes. After the server side of the feedback information, timely update to the Post button, give users a good experience.

Optimization

It's basically a chat that you can get done here. But the effect of implementation will be very bad, mainly have the following points.
• No scrolling display, each time you have to manually view the latest news.
• The data obtained has a lot of duplicate data, both waste traffic and inconvenient to view information.

Show data that is not repeatable

For data that shows repeatability, this is because we don't use the where statement, and it seems like every time we get all the data. Imagine how to get the latest data?
And for different clients are to be taken care of.

Hollywood rule: Don't come to me, I'll find you.

This is also a reflection of many software development concepts, allowing customers to decide what data to acquire, rather than server-side beat him. So we need to be optimized for sending data requests from the client.

<script>//Record the maximum number of IDs currently obtained to prevent duplicate information from being obtained var maxid = 0;
  function ShowMessage () {var ajax = new XMLHttpRequest (); 
      Fetch and process data Ajax.onreadystatechange = function () {if (ajax.readystate==4) {//alert (Ajax.responsetext) from the server;
      Converts the acquired string to entity eval (' var data = ' +ajax.responsetext);
      Traversal of the data array, the internal information is displayed to the page of 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+ "said:" + data[i].msg;
        S + + "</p>";
      Update the maximum record ID that has been obtained maxid = data[i].id;
      ///Start appending information to page var showmessage = document.getElementById ("Up");
      showmessage.innerhtml = s; Showmessage.scrolltop can implement Div bottom first show//Divnode.scrollheight just get the height of the div including the height of the scroll bar showmessage.scrolltop = ShowMe Ssage.scrollheighT-showmessage.style.height;
  } ajax.open (' Get ', './chatroom.php?maxid= ' +maxid);  

Ajax.send (NULL);  
  }//Update the timing of the information window.onload = function () {//showmessage ();
Make polling, realize automatic page update setinterval ("ShowMessage ()", 3000);

 } </script>

Optimized display

The optimization of the display interface is essential, and no one can tolerate sending a single piece of data and having to manually view the latest news. So we're going to set the div for the display area.

Plus scroll bar

<style>
  #up {
    height:320px;
    width:100%;
    Overflow:auto; 
  }
</style>

Every time the latest message is displayed

The bottom of the div is always the first to display.

Showmessage.scrolltop can implement Div bottom first show
//Divnode.scrollheight just get the height of the div, including the height of the scroll bar
showmessage.scrolltop = Showmessage.scrollheight-showmessage.style.height;

Complete code

Front-end Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

database table Structure

mysql> desc message;
+----------+--------------+------+-----+---------+----------------+
| Field  | Type     | Null | Key | Default | Extra     |
+----------+--------------+------+-----+---------+----------------+
| ID    | int (MB)   | 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

//Get the latest chat information
$conn = mysql_connect (' localhost ', ' root ', ' MySQL ');
mysql_select_db (' test ');
mysql_query (' Set names UTF8 ');

$maxId = $_get[' Maxid '];

Prevents duplicate data from being obtained, the record result ID for this request is large fish the last obtained id
$sql = "SELECT * from message where ID >". " $maxId ' ";
$qry = mysql_query ($sql);

$info = Array ();
while ($rst = Mysql_fetch_assoc ($qry)) {
  $info [] = $rst;
}


Provide data
echo Json_encode ($info) to clients via JSON format;


? >

Summary and Prospect

Summarize

The complete small example is the case. In retrospect, today's harvest is:
• How to poll for data, with the help of the SetInterval function
• Timed vanishing hint data, with the help of the settimeout function
• How to get the latest data: There are MAXID parameters sent by the client control.
• How to optimize display: overflow to achieve scrolling effect; Divnode.scrolltop control shows bottom effects

Prospect
• Perhaps you will find that the client sender is fixed, that is because we do not do user login. If you do a user login, our sender can be dynamically obtained from the session. This can also be more in line with people's subjective feelings.

• The interface is bad, no landscaping effect. The effect should be great after adding bootstrap.

• Phone adapter effect is not good, in addition to the WindowsPhone color control can not be normal display.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.