PHP&是可能的吗? AJAX会两次插入一个查询?

时间:2013-09-04 20:06:16

标签: php jquery ajax pdo

所以我正在用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>

data.php

<?php

include 'pdo.config.php';


$chat = $PDO->query("SELECT * FROM `chatbox`");
$getRow = $chat->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($getRow);

?>

1 个答案:

答案 0 :(得分:0)

下一步是检查你的access.log以确保你没有从某个地方获得双重POST到shout.php

可能还有其他帖子在雷达下滑落。