【问题标题】:PHP chat form redirects using AjaxPHP 聊天表单使用 Ajax 重定向
【发布时间】:2015-07-10 08:42:32
【问题描述】:

我正在与几个文件进行简单的聊天:

  • chat.php - 带有用户名和消息字段的表单,以及带有操作的提交按钮:chat_send.php。
  • chat_send.php - 将用户名和消息插入数据库。
  • chat_receive.php - 读取数据库的文件

问题是我无法在不重新加载的情况下使其工作。我知道我应该使用 Ajax,但是我输入的代码根本不起作用。它应该从数据库中读取消息,并且在不刷新页面的情况下在聊天框中显示消息。我的问题在哪里?

脚本

$(document).ready(function() {
  $('#send').submit(function(e) {
    e.preventDefault();     
    var url = $(this).attr('action');
    var data = $(this).serialize();  
    $.post(url, data)
      .done( function(response) {
        $('#response').html(response);
      })
      .fail( function() {
        alert("The AJAX request failed!");
      });
  });
});

CHAT.PHP

<form action="chat_send.php" method="post" class="send" id="form1" >
  <p>
    <label for="name">Name:</label>
    <input type="text" name="name" id="name">
  </p>
  <div style="width: 480px; height: 400px; border-right: darkslategray thin solid; border-top: darkslategray thin solid; font-size: 10pt; border-left: darkslategray thin solid; border-bottom: darkslategray thin solid; font-family: verdana, arial; overflow:scroll; text-align: left;" id="DIV_CHAT">
  </div>
    <p>
    <label for="emailAddress"></label>
    <textarea id="msg" rows="5" cols="66" name="msg" placeholder="Your Message"></textarea></p>
    </p>
  <input class="submit" type="submit" id="button1" name="submit" value="Send" onfocus="this.blur()"  />
</form>

CHAT_SEND.PHP

if(!isset($_POST['submit'])) {}else
  {
    $name = mysqli_real_escape_string( $mysqli,$_POST['name']);
    $msg = mysqli_real_escape_string($mysqli, $_POST['msg']);
    $dt = date("Y-m-d H:i:s");
      $sql = "INSERT INTO messages (username, chatdate, msg) VALUES ('$name', '$dt', '$msg')";
      mysqli_query($mysqli, $sql);
}
    $mysqli->close();

CHAT_RECEIVE.PHP

  $sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r') as cdt from messages order by ID desc limit 200";
  $result = $mysqli->query(  "SELECT * FROM (" . $sql . ") as ch order by id");
  $msg="<table border='0' style='font-size: 10pt; color: blue; font-family: verdana, arial;'>";
     while ($line = $result->fetch_array())
     {
           $msg = $msg . "<tr><td>" . $line["cdt"] . "&nbsp;</td>" .
                "<td>" . $line["username"] . ":&nbsp;</td>" .
                "<td>" . $line["msg"] . "</td></tr>";
     }
     $msg=$msg . "</table>";
     echo $msg;

我已经尝试了所有 stackoverflow Ajax 解决方案,但都没有成功。

【问题讨论】:

  • 创建一个向 CHAT_RECEIVE.php 发出 AJAX 请求的 JavaScript 函数,然后定期调用此函数 - 比如说每 10 秒一次。您可以将捎带和无限期连接作为检查新消息的替代方法。

标签: php jquery ajax forms mysqli


【解决方案1】:

我能看到的最明显的事情是您的表单$('#send') 的jQuery 选择器不匹配,因为表单的ID 是form1,类是send,所以要么更改为$('.send')$('#form1')

【讨论】:

  • 实际上,改变这个 -> 我的提交按钮不起作用:(
  • 在控制台中检查 AJAX 请求是否通过...e.preventDefault() 将阻止表单实际提交,但它应该是这样工作的。
猜你喜欢
  • 1970-01-01
  • 2010-11-08
  • 2011-07-12
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
相关资源
最近更新 更多