【问题标题】:Is it possible for PHP & AJAX to clash an insert a query twice?PHP 和 AJAX 是否有可能两次崩溃插入查询?
【发布时间】: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语句[和块在页面顶部] 提供输出,然后发送标题。我不指望它能解决问题,但没有其他潜在的问题会出现在我身上。

标签: php jquery ajax pdo


【解决方案1】:

下一步是检查您的 access.log 以确保您没有从某处获得双重 POST 到喊叫.php

可能还有其他正在发生的帖子被忽视了。

【讨论】:

    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2014-01-09
    • 2019-08-07
    相关资源
    最近更新 更多