Ajax PHP JavaScript MySQL implementation simple no refresh online chat room

Source: Internet
Author: User
Tags ajax chat
This article mainly introduces the Ajax PHP JavaScript MySQL implementation of simple no-refresh online chat room, with a certain reference value, interested in small partners can refer to

In order to better use the knowledge of Ajax learned in these two days, we made a simple online chat room.

Ideas

Implementation of the chat room, basically through the Ajax to pass the data, so that PHP to achieve the difference in data and find, and then to the front-end JavaScript to achieve the page update, to achieve the function of instant chat.

Message display Area

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


Send Message

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

Plate

The following begins the use of 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 ();  Gets and processes data from the server  Ajax.onreadystatechange = function () {    if (ajax.readystate==4) {      //alert ( Ajax.responsetext);       Converts the acquired string to the entity      eval (' var data = ' +ajax.responsetext);      Iterate through the data array and display the internal information to the page      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 + "on" + Data[i].receiver + "  + data[i].biaoqing+" said: "+ data[i].msg;        s + = "</p>";      }      Append information to the page when you start      var showmessage = document.getElementById ("Up");      Showmessage.innerhtml + = s;    }  }  Ajax.open (' Get ', './chatroom.php ');  Ajax.send (null);  } Update information execution Time window.onload = function () {  //showmessage ();    Make polling for automatic page update  setinterval ("ShowMessage ()", 3000);} </script>


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

Send Message

About message sending, sent to the server by Form. We use a current HTML5 of the latest technology, FormData, in general, the current mainstream of modern browsers are supporting this technology. With Formdata we can easily get the data for a form.

Note: Formdata collects the form data in the form of key-value pairs, so the corresponding table item must have the name attribute, otherwise the form will not collect the data value of the item.


<script>  function Send () {    //to server-related 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 ()", "N");}    }    Xhr.open (' Post ', './chatroom_insert.php ');    Xhr.send (formdata);    document.getElementById ("msg"). value= "";    return false;  }  The Vanishing  function Hideresult () {document.getElementById (' result ') that implements the message after 2 seconds    . InnerHTML = "";    } </script>

It is worth pondering: the function that settimeout function realizes. After receiving the feedback from the server side, it is timely to update the Post button to give the user a good experience.

Optimization

You can basically chat after you've done this. But the implementation of the effect will be very bad, mainly has the following points.
• There is no scrolling and you have to manually view the latest news every time.
• The data obtained has a lot of duplicate data, which is wasteful of traffic and is not easy to view information.

Show non-repeatable data

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

Hollywood principles: 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 get, rather than server-side beat him. So we need to optimize for sending data requests to the client.

<script>//records the maximum value of the currently acquired ID, preventing getting to duplicate information var Maxid = 0;function ShowMessage () {var ajax = new XMLHttpRequest ();       Gets and processes data from the server Ajax.onreadystatechange = function () {if (ajax.readystate==4) {//alert (ajax.responsetext);      Converts the acquired string to the entity eval (' var data = ' +ajax.responsetext);      Iterate through the data array and display the internal information to the page 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 + "on" + data[i].receiver + "+ data[i].biaoqing+" said: "+ data[i].msg;        s + = "</p>";      Update Maxid = Data[i].id for the largest record ID that has been obtained;      }//Start appending information to the page var showmessage = document.getElementById ("Up");      Showmessage.innerhtml + = s; Showmessage.scrolltop can achieve P bottom first show//Pnode.scrollheight just get the height of p including the height of the scroll bar showmessage.scrolltop = Showmessage.sc    Rollheight-showmessage.style.height; }} ajax.open (' Get ', './chatroom.php?maxid= ' +maxid);  Ajax.send (NULL);    }//update information Execution Time window.onload = function () {//showmessage (); Make polling for automatic page update setinterval ("ShowMessage ()", 3000);} </script>


Optimized display

Optimizing the display interface is essential, and no one can tolerate the need to manually view the latest messages after sending a single piece of data. So we're going to set the p for the display area.

Plus scroll bar

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

Show the latest news every time

To put it bluntly is to let the bottom p always show first.

Showmessage.scrolltop can achieve P bottom first show//Pnode.scrollheight just get the height of p including the height of the scroll bar showmessage.scrolltop = Showmessage.scrollheight-showmessage.style.height;

Full 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   | 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 '];//to prevent the acquisition of duplicate data, the record result ID of this request to be large fish 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 to the client in JSON format echo json_encode ($info);? >


Summary and Prospect

Summarize

This is the case with a complete small example. To recap, today's harvest is:
• How to poll for data, with the help of the SetInterval function
• Data for timed vanishing prompts, with the help of the settimeout function
• How to get the latest data: There are client control Maxid parameters sent.
• How to optimize the display: overflow to achieve scrolling effect; pnode.scrolltop control display Bottom effect

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

• The interface does not make the comparison rotten, does not add beautification effect. Add bootstrap after the effect should be very good.

• The phone does not fit well, and the color controls on the WindowsPhone are not displayed properly.

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.