简体   繁体   English

如何实现实时实时消息传递jQuery Ajax Mysql Php

[英]How to implement real-time live messaging jQuery Ajax Mysql Php

I'm writting a very simple chat application. 我正在编写一个非常简单的聊天应用程序。 I have written a code that works at inserting data in database without refreshing the page. 我编写了一个代码,该代码可在不刷新页面的情况下在数据库中插入数据。 But when I test with two users at the same time, I can only see what the other user sent to me when I send a new message. 但是,当我同时与两个用户进行测试时,我只能在发送新消息时看到另一个用户向我发送的内容。 How can I make it more live? 如何使它更生动? I spent the entire day reading on Websockets (specifically socket.io, ratchet) and long-polling. 我整天都在阅读Websockets(特别是socket.io,棘轮)和长时间轮询。 I found interesting solutions around here but I'm looking to implement it with the code I have already written and it's confusing me. 我在这里找到了有趣的解决方案,但是我希望使用已经编写的代码来实现它,这使我感到困惑。 I'm using a php while statement to get data from database. 我正在使用php while语句从数据库获取数据。

Working Ajax code 工作的Ajax代码

<script>
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: true,
success: function(response){
   $("#displayMessage").html(response);
       $("#chatForm").trigger("reset");
}
});

return false;
});
});
    </script>

while statement while语句

       <div id='displayMessage' style='height: 480px; padding:5%; overflow-x:hidden;'>
        <?php
            $chatmsgQ="SELECT * FROM ve_chat c 
   WHERE c.isActive='1' AND (c.fromUserId='$loginid_session' 
   OR c.toUserId='$loginid_session')";
$chatmsgresult=  mysqli_query($db,$chatmsgQ);
        while($chatmsg=  mysqli_fetch_array($chatmsgresult)){?>
   <?php if($chatmsg['fromUserId']==$loginid_session):?>
   <!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
  <!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
  </div>

PHP isn't really the best language to use when it comes to push messages, it's really built around typical get/response kinda flows. PHP并不是真正用于推送消息的最佳语言,它实际上是基于典型的获取/响应类流程构建的。

http://www.nodejs.org and http://socket.io/ hey're very easy to get setup, and will play well with you using php for the majority of your work, then using node to deal with push messages kinda stuff. http://www.nodejs.orghttp://socket.io/非常容易设置,并且在大多数工作中使用php与您一起玩得很好,然后使用node处理推送消息有点东西。

To make your application more live, you need to use setInterval method. 为了使您的应用程序更加生动,您需要使用setInterval方法。 Use this project Simple php, ajax and mysql chat application. 使用此项目的简单php,ajax和mysql聊天应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM