PHP implementation of the simplest chat room application

Source: Internet
Author: User
Tags date http request sql php and query return window ajax chat

Introduced

Chat applications are very common on the web. Developers also have a lot of choices in building this type of application. This article describes how to implement a Php-ajax chat application and can send and receive messages without having to refresh the page.

Core Logic

Before defining the core functionality of your application, take a look at the basic look of the chat application, as shown in the screenshot below:

Enter the chat text through the input box at the bottom of the chat window. Click the Send button to start the function set_chat_msg. This is an AJAX based function, so you can send chat text to the server without refreshing the page. The program executes chat_send_ajax.php and user name and chat text in the server.

 
 
  1. //
  2. Set Chat Message
  3. //
  4. function set_chat_msg ()
  5. {
  6. if (typeof XMLHttpRequest!= "undefined")
  7. {
  8. Oxmlhttpsend = new XMLHttpRequest ();
  9. }
  10. else if (window. ActiveXObject)
  11. {
  12. Oxmlhttpsend = new ActiveXObject ("Microsoft.XMLHTTP");
  13. }
  14. if (oxmlhttpsend = null)
  15. {
  16. Alert ("Browser does not support XML Http Request");
  17. Return
  18. }
  19. var url = "chat_send_ajax.php";
  20. var strname= "Noname";
  21. var strmsg= "";
  22. if (document.getElementById ("txtname")!= null)
  23. {
  24. strname = document.getElementById ("Txtname"). Value;
  25. document.getElementById ("Txtname"). Readonly=true;
  26. }
  27. if (document.getElementById ("txtmsg")!= null)
  28. {
  29. strmsg = document.getElementById ("txtmsg"). Value;
  30. document.getElementById ("Txtmsg"). Value = "";
  31. }
  32. url = "? name=" + strname + "&msg=" + strmsg;
  33. Oxmlhttpsend.open ("Get", url,true);
  34. Oxmlhttpsend.send (NULL);
  35. }

The PHP module receives form data from the query string, which is updated to the database table named Chat. The Chat database table has ID columns named, USERNAME ,, CHATDATE and MSG . The ID field is an automatically incremented field, so the assignment of this ID field is incremented automatically. The current date and time are updated to the Chatdate column.

 
 
  1. Require_once (' dbconnect.php ');
  2. Db_connect ();
  3. $msg = $_get["MSG"];
  4. $DT = Date ("y-m-d h:i:s");
  5. $user = $_get["name"];
  6. $sql = "INSERT into chat (username,chatdate,msg)".
  7. "VALUES (". QUOTE ($user). "," .
  8. QUOTE ($DT). "," . QUOTE ($MSG). ");";
  9. Echo $sql;
  10. $result = mysql_query ($sql);
  11. if (! $result)
  12. {
  13. throw new Exception (' Query failed: '. mysql_error ());
  14. Exit ();
  15. }

To receive chat messages from all users in the database table, the timer function is set to loop 5 seconds to invoke the following JavaScript command, which is to perform the get_chat_msg function 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 property, another JavaScript function get_chat_msg_result is connected. Program control enters the Get_chat_msg_result function while returning the chat message from the database table.

 
 
  1. //
  2. General Ajax Call
  3. //
  4. var oxmlhttp;
  5. var oxmlhttpsend;
  6. function get_chat_msg ()
  7. {
  8. if (typeof XMLHttpRequest!= "undefined")
  9. {
  10. Oxmlhttp = new XMLHttpRequest ();
  11. }
  12. else if (window. ActiveXObject)
  13. {
  14. Oxmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
  15. }
  16. if (oxmlhttp = null)
  17. {
  18. Alert ("Browser does not support XML Http Request");
  19. Return
  20. }
  21. Oxmlhttp.onreadystatechange = Get_chat_msg_result;
  22. Oxmlhttp.open ("Get", "chat_recv_ajax.php", true);
  23. Oxmlhttp.send (NULL);
  24. }

In the chat_recv_ajax.php program, chat messages from users are collected through SQL select commands. To limit the number of rows, a restriction clause (limit 200) is also given in the SQL query, which requires the last 200 rows in the Chat database table. The received message is then returned to the AJAX function to display the content in the Chat window.

 
 
  1. Require_once (' dbconnect.php ');
  2. Db_connect ();
  3. $sql = "SELECT *, Date_format (chatdate, '%d-%m-%y%r ')
  4. As CDT from chat ORDER by ID desc limit 200 ";
  5. $sql = "SELECT * from". $sql. ") as Ch order by ID";
  6. $result = mysql_query ($sql) or Die (' Query failed: '. mysql_error ());
  7. Update Row Information
  8. $msg = "";
  9. while ($line = Mysql_fetch_array ($result, MYSQL_ASSOC))
  10. {
  11. $msg = $msg. "" .
  12. "" .
  13. "";
  14. }
  15. $msg = $msg. "<table style=" color:blue; Font-family:verdana, Arial; " .
  16. "font-size:10pt" border= "0" >
  17. <tbody><tr><td> ". $line [CDT].
  18. "</td><td>". $line ["username"].
  19. ": </td><td>". $line ["MSG"].
  20. "</td></tr></tbody></table>";
  21. Echo $msg;
  22. As the data is ready, the JavaScript function collects the data from the PHP received. The data will be placed inside the div tag. Oxmlhttp.responsetext will retain the chat message received from the PHP program and copy it to the document.getElementById ("Div_chat") of the DIV tag. innerHTML properties.
  23. function Get_chat_msg_result (t)
  24. {
  25. if (oxmlhttp.readystate==4 oxmlhttp.readystate== "complete")
  26. {
  27. if (document.getElementById ("div_chat")!= null)
  28. {
  29. document.getElementById ("Div_chat"). InnerHTML = Oxmlhttp.responsetext;
  30. Oxmlhttp = null;
  31. }
  32. var scrolldiv = document.getElementById ("Div_chat");
  33. Scrolldiv.scrolltop = Scrolldiv.scrollheight;
  34. }
  35. }

The following SQL CREATE TABLE command can be used to create a database table named Chat. All information entered by the user is entered into the database table.

CREATE TABLE Chat (id bigint auto_increment,username varchar (20),
chatdate datetime,msg varchar (), primary key (ID));

Points of interest

This code for implementing the chat application is very interesting. It can be improved into a fully fledged HTTP chat application. The logic for creating the application is also very simple. Even beginners will not have any difficulty understanding it.

License

This article, along with any related source code and files, is licensed by the Code Project Open License (Cpol).

Translation Links: http://www.codeceo.com/article/php-chart-app.html
English Original: Chat application in PHP

"Responsible Editor: Wangxueyan TEL: (010) 68476606"


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.