【发布时间】:2013-09-04 20:06:15
【问题描述】:
所以我正在用 PHP/PDO/AJAX 制作一个基本的聊天框,最近当我添加 AJAX 代码并提交我的喊叫时,它运行了两次查询,我检查了我的代码,检查员说他们可以没看出有什么不对。所以我想知道你是否可以帮我找到错误。
shout.php
<html>
<head>
<title>Shout!</title>
<link rel="stylesheet" href="CSS/styles.css"/>
</head>
</html>
<?php
include 'auth.login.php';
include 'pdo.config.php';
if (!isset($_SESSION['Username'])) {
echo '<br/>';
echo '<center>You need to login to post!<br/>';
header("Refresh:2; URL=index.php");
exit();
}
$Username = $_SESSION['Username'];
if (!isset($_POST['Message']) || empty($_POST['Message'])) {
echo '<br/>';
echo '<center>How do you expect to send a message if the field is empty, ey?<br/>';
header("Refresh:2; URL=index.php");
exit();
} else {
$Message = htmlspecialchars($_POST['Message']);
$insertMessage = $PDO->prepare("INSERT INTO `chatbox` (User, Message) VALUES (?, ?)");
$insertMessage->bindParam(1, $Username, PDO::PARAM_STR);
$insertMessage->bindParam(2, $Message, PDO::PARAM_STR);
if ($insertMessage->execute()) {
header("Location: index.php");
exit();
} else {
echo '<br/>';
echo '<center>Aw snap, shout could not be added!';
header("Refresh:2; URL=index.php");
exit();
}
}
?>
main.js
$(document).ready(function(){
$.ajax({
url: 'data.php',
data: '',
dataType: 'json',
type: 'GET',
success: function(data)
{
$.each(data, function (idx, elem) {
$('#messageDisplay').append("<div>["+elem.SentOn+"] "+elem.User+": "
+ elem.Message + "</div>");
});
}
});
});
我的表格:
<form action="shout.php" method="post">
<textarea rows="8" cols="74" id="Message" name="Message" placeholder="Post messages here."></textarea>
<br/><input type="submit" id="submit" value="Shout!">
</form>
数据.php
<?php
include 'pdo.config.php';
$chat = $PDO->query("SELECT * FROM `chatbox`");
$getRow = $chat->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($getRow);
?>
【问题讨论】:
-
@djot,添加了 data.php。
-
"my form:" -- 表单在哪个文件,index.php?
-
除了shout.php在关闭html标签后输出html之外,我没有看到任何错误。
-
@developerwjk,是的。
-
为了我的好奇心,你能否在你的 header() 被发送到shout.php之前删除输出 - 我正在专门查看
execute条件的else语句[和块在页面顶部] 提供输出,然后发送标题。我不指望它能解决问题,但没有其他潜在的问题会出现在我身上。