ajax即时聊天程序
How to Easily Make “Ajaxy” Chat application with PHP + SQL + jQuery
如何使用PHP + SQL + jQuery轻松制作“ Ajaxy”聊天应用程序
Today I will tell you about another chat system. After making old-style chat described in previous post I decided to make modern, pretty version. I made several enhancements:
今天,我将告诉您另一个聊天系统。 在完成上一篇文章中描述的老式聊天之后,我决定制作现代漂亮的版本。 我做了一些改进:
So, as result – we will able to chat with our logged members. We will use database to store messages as usual. Here is a sample:
因此,结果–我们将能够与登录的会员聊天。 我们将照常使用数据库来存储消息。 这是一个示例:
[sociallocker]
[社交储物柜]
[/sociallocker]
[/ sociallocker]
Ok, download the example files and lets start coding !
好的,下载示例文件并开始编码!
As usual, we start with the HTML.
和往常一样,我们从HTML开始。
This is input text form of our chat.
这是我们聊天的输入文本形式。
<form class="submit_form" method="post" action="" target="chat_res">
<div><input type="text" name="s_message" /><input type="submit" value="Say" name="s_say" /></div>
</form>
<div>You can type anything in chat</div>
<iframe name="chat_res" style="display:none;"></iframe>
<form class="submit_form" method="post" action="" target="chat_res">
<div><input type="text" name="s_message" /><input type="submit" value="Say" name="s_say" /></div>
</form>
<div>You can type anything in chat</div>
<iframe name="chat_res" style="display:none;"></iframe>
This is login form code.
这是登录表单代码。
<form class="login_form" method="post" action="">
<div>Username: <input type="text" name="username" /></div>
<div>Password: <input type="password" name="password" /></div>
<div><input type="submit" value="Login" name="Login" /></div>
</form>
<div>You can use username "User1" or "User2" and password "qwerty" to login in system</div>
<hr />
<form class="login_form" method="post" action="">
<div>Username: <input type="text" name="username" /></div>
<div>Password: <input type="password" name="password" /></div>
<div><input type="submit" value="Login" name="Login" /></div>
</form>
<div>You can use username "User1" or "User2" and password "qwerty" to login in system</div>
<hr />
Here are used CSS styles.
这是使用CSS样式。
.login_form {
border: 1px solid #AAA;
padding:10px;
}
h3 {margin-top:3px;}
.chat_main {
border:1px solid #AAA;
-moz-box-shadow:0 0 10px #ccc;
-webkit-box-shadow: 0 0 10px #ccc;
width:350px;
padding:10px;
background:#f3f3f3;
}
.message {
border:1px solid #AAA;
margin:4px;
padding:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#ffffff;
}
.textf {-moz-box-shadow:0 0 10px #CCCCCC;
-webkit-box-shadow:0 0 10px #CCCCCC;
border:1px solid #CCCCCC;
height:40px;}
.submit {
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#F3F3F3;
border:1px solid #CCCCCC;
font-size:16px;
font-weight:bold;
height:35px;
margin-left:10px;
padding:5px;
}
.message span {
font-size:10px;
color:#888;
margin-left:10px;
}
.submit_form {
margin:10px 0px;
}
.login_form {
border: 1px solid #AAA;
padding:10px;
}
h3 {margin-top:3px;}
.chat_main {
border:1px solid #AAA;
-moz-box-shadow:0 0 10px #ccc;
-webkit-box-shadow: 0 0 10px #ccc;
width:350px;
padding:10px;
background:#f3f3f3;
}
.message {
border:1px solid #AAA;
margin:4px;
padding:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#ffffff;
}
.textf {-moz-box-shadow:0 0 10px #CCCCCC;
-webkit-box-shadow:0 0 10px #CCCCCC;
border:1px solid #CCCCCC;
height:40px;}
.submit {
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#F3F3F3;
border:1px solid #CCCCCC;
font-size:16px;
font-weight:bold;
height:35px;
margin-left:10px;
padding:5px;
}
.message span {
font-size:10px;
color:#888;
margin-left:10px;
}
.submit_form {
margin:10px 0px;
}
We will need to execute next SQL in our database.
我们将需要在数据库中执行下一个SQL。
CREATE TABLE `s_ajax_chat_messages` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`member_id` INT( 11 ) NOT NULL ,
`member_name` VARCHAR( 255 ) NOT NULL ,
`message` VARCHAR( 255 ) NOT NULL ,
`when` INT( 11 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `s_members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`pass` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `s_members` (`id`, `name`, `pass`) VALUES
(NULL, 'User1', 'd8578edf8458ce06fbc5bb76a58c5ca4'),
(NULL, 'User2', 'd8578edf8458ce06fbc5bb76a58c5ca4');
CREATE TABLE `s_ajax_chat_messages` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`member_id` INT( 11 ) NOT NULL ,
`member_name` VARCHAR( 255 ) NOT NULL ,
`message` VARCHAR( 255 ) NOT NULL ,
`when` INT( 11 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `s_members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`pass` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `s_members` (`id`, `name`, `pass`) VALUES
(NULL, 'User1', 'd8578edf8458ce06fbc5bb76a58c5ca4'),
(NULL, 'User2', 'd8578edf8458ce06fbc5bb76a58c5ca4');
Here are few necessary JS files to our project.
这是我们项目所需的一些JS文件。
$(function() {
getMessages = function() {
var self = this;
var _sRandom = Math.random();
$.getJSON('index.php?action=get_last_messages' + '&_r=' + _sRandom, function(data){
if(data.messages) {
$('.chat_main').html(data.messages);
}
// start it again;
setTimeout(function(){
getMessages();
}, 5000);
});
}
getMessages();
});
$(function() {
getMessages = function() {
var self = this;
var _sRandom = Math.random();
$.getJSON('index.php?action=get_last_messages' + '&_r=' + _sRandom, function(data){
if(data.messages) {
$('.chat_main').html(data.messages);
}
// start it again;
setTimeout(function(){
getMessages();
}, 5000);
});
}
getMessages();
});
This classe are general – jQuery library. No need to give full code of that file here. It always available as a download package
此类是通用的– jQuery库。 无需在此处提供该文件的完整代码。 它始终可以作为下载包获得
I hope that most code will easy for your understanding – each function have normal name and commented.
我希望大多数代码都能使您容易理解-每个函数都有正常的名称和注释。
Ok, here are all used PHP files:
好的,这是所有使用过PHP文件:
<?php
// set error reporting level
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
error_reporting(E_ALL & ~E_NOTICE);
require_once('inc/db.inc.php');
require_once('inc/login.inc.php');
require_once('inc/ajx_chat.inc.php');
if ($_REQUEST['action'] == 'get_last_messages') {
$sChatMessages = $GLOBALS['AjaxChat']->getMessages(true);
require_once('inc/Services_JSON.php');
$oJson = new Services_JSON();
echo $oJson->encode(array('messages' => $sChatMessages));
exit;
}
// draw login box
echo $GLOBALS['oSimpleLoginSystem']->getLoginBox();
// draw exta necessary files
echo '<link type="text/css" rel="stylesheet" href="templates/css/styles.css" />';
echo '<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>';
echo '<script type="text/javascript" src="js/main.js"></script>';
// draw chat messages
$sChatMessages = $GLOBALS['AjaxChat']->getMessages();
// draw input form + accept inserted texts
$sChatInputForm = 'Need login before using';
if ($GLOBALS['bLoggedIn']) {
$sChatInputForm = $GLOBALS['AjaxChat']->getInputForm();
$GLOBALS['AjaxChat']->acceptMessages();
}
echo $sChatMessages . $sChatInputForm;
?>
<?php
// set error reporting level
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
error_reporting(E_ALL & ~E_NOTICE);
require_once('inc/db.inc.php');
require_once('inc/login.inc.php');
require_once('inc/ajx_chat.inc.php');
if ($_REQUEST['action'] == 'get_last_messages') {
$sChatMessages = $GLOBALS['AjaxChat']->getMessages(true);
require_once('inc/Services_JSON.php');
$oJson = new Services_JSON();
echo $oJson->encode(array('messages' => $sChatMessages));
exit;
}
// draw login box
echo $GLOBALS['oSimpleLoginSystem']->getLoginBox();
// draw exta necessary files
echo '<link type="text/css" rel="stylesheet" href="templates/css/styles.css" />';
echo '<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>';
echo '<script type="text/javascript" src="js/main.js"></script>';
// draw chat messages
$sChatMessages = $GLOBALS['AjaxChat']->getMessages();
// draw input form + accept inserted texts
$sChatInputForm = 'Need login before using';
if ($GLOBALS['bLoggedIn']) {
$sChatInputForm = $GLOBALS['AjaxChat']->getInputForm();
$GLOBALS['AjaxChat']->acceptMessages();
}
echo $sChatMessages . $sChatInputForm;
?>
This is our Chat class
这是我们的聊天课
<?php
/**
* Simple ajaxy chat class
*/
class SimpleAjaxyChat {
/**
* constructor
*/
function SimpleAjaxyChat() {}
/**
* Adding to DB table posted message
*/
function acceptMessages() {
$sUsername = $GLOBALS['aLMemInfo']['name'];
$iUserID = (int)$GLOBALS['aLMemInfo']['id'];
if($sUsername && isset($_POST['s_message']) && $_POST['s_message'] != '') {
$sMessage = $GLOBALS['MySQL']->process_db_input($_POST['s_message'], A_TAGS_STRIP);
if ($sMessage != '') {
$GLOBALS['MySQL']->res("INSERT INTO `s_ajax_chat_messages` SET `member_id`='{$iUserID}', `member_name`='{$sUsername}', `message`='{$sMessage}', `when`=UNIX_TIMESTAMP()");
}
}
}
/**
* Return input text form
*/
function getInputForm() {
ob_start();
require_once('templates/chat_input.html');
return ob_get_clean();
}
/**
* Return last 15 messages
*/
function getMessages($bOnlyMessages = false) {
$aMessages = $GLOBALS['MySQL']->getAll("SELECT `s_ajax_chat_messages`.*, `s_members`.`name`, UNIX_TIMESTAMP()-`s_ajax_chat_messages`.`when` AS 'diff' FROM `s_ajax_chat_messages` INNER JOIN `s_members` ON `s_members`.`id` = `s_ajax_chat_messages`.`member_id` ORDER BY `id` DESC LIMIT 15");
$sMessages = '';
// collecting list of messages
foreach ($aMessages as $iID => $aMessage) {
$sExStyles = $sExJS = '';
$iDiff = (int)$aMessage['diff'];
if ($iDiff < 7) {
$sExStyles = 'style="display:none;"';
$sExJS = "<script> $('#message_{$aMessage['id']}').slideToggle('slow'); </script>";
}
$sWhen = date("H:i:s", $aMessage['when']);
$sMessages .= '<div class="message" id="message_'.$aMessage['id'].'" '.$sExStyles.'>' . $aMessage['name'] . ': ' . $aMessage['message'] . '<span>(' . $sWhen . ')</span></div>' . $sExJS;
}
if ($bOnlyMessages) return $sMessages;
return '<h3>Ajaxy Chat</h3><div class="chat_main">' . $sMessages . '</div>';
}
}
$GLOBALS['AjaxChat'] = new SimpleAjaxyChat();
?>
<?php
/**
* Simple ajaxy chat class
*/
class SimpleAjaxyChat {
/**
* constructor
*/
function SimpleAjaxyChat() {}
/**
* Adding to DB table posted message
*/
function acceptMessages() {
$sUsername = $GLOBALS['aLMemInfo']['name'];
$iUserID = (int)$GLOBALS['aLMemInfo']['id'];
if($sUsername && isset($_POST['s_message']) && $_POST['s_message'] != '') {
$sMessage = $GLOBALS['MySQL']->process_db_input($_POST['s_message'], A_TAGS_STRIP);
if ($sMessage != '') {
$GLOBALS['MySQL']->res("INSERT INTO `s_ajax_chat_messages` SET `member_id`='{$iUserID}', `member_name`='{$sUsername}', `message`='{$sMessage}', `when`=UNIX_TIMESTAMP()");
}
}
}
/**
* Return input text form
*/
function getInputForm() {
ob_start();
require_once('templates/chat_input.html');
return ob_get_clean();
}
/**
* Return last 15 messages
*/
function getMessages($bOnlyMessages = false) {
$aMessages = $GLOBALS['MySQL']->getAll("SELECT `s_ajax_chat_messages`.*, `s_members`.`name`, UNIX_TIMESTAMP()-`s_ajax_chat_messages`.`when` AS 'diff' FROM `s_ajax_chat_messages` INNER JOIN `s_members` ON `s_members`.`id` = `s_ajax_chat_messages`.`member_id` ORDER BY `id` DESC LIMIT 15");
$sMessages = '';
// collecting list of messages
foreach ($aMessages as $iID => $aMessage) {
$sExStyles = $sExJS = '';
$iDiff = (int)$aMessage['diff'];
if ($iDiff < 7) {
$sExStyles = 'style="display:none;"';
$sExJS = "<script> $('#message_{$aMessage['id']}').slideToggle('slow'); </script>";
}
$sWhen = date("H:i:s", $aMessage['when']);
$sMessages .= '<div class="message" id="message_'.$aMessage['id'].'" '.$sExStyles.'>' . $aMessage['name'] . ': ' . $aMessage['message'] . '<span>(' . $sWhen . ')</span></div>' . $sExJS;
}
if ($bOnlyMessages) return $sMessages;
return '<h3>Ajaxy Chat</h3><div class="chat_main">' . $sMessages . '</div>';
}
}
$GLOBALS['AjaxChat'] = new SimpleAjaxyChat();
?>
All these classes are general in nature and is large enough that we will not describe them here, but they are always available as a download package
所有这些类本质上都是通用的,足够大,我们在这里不再对其进行描述,但是它们始终可以作为下载包获得。
Today I told you how to create own simple and good ajaxy chat application based on PHP, MySQL, jQuery and JSON a little. You can use this material to create own scripts into your startups. Good luck!
今天,我告诉您一些如何基于PHP,MySQL,jQuery和JSON创建自己的简单且良好的Ajaxy聊天应用程序。 您可以使用此材料在创业公司中创建自己的脚本。 祝好运!
翻译自: https://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/
ajax即时聊天程序