无法连接 Jquery Ajax POST 到 PHP 页面

3
php
<?php

include 'connection.php';
echo "reached page";
$stmt = $conn->prepare("INSERT INTO flagged ( ID,URL,COUNT,comment)VALUES ( :id,    :url, :count,:COMMENT )"); 
$stmt->bindParam(':id', $id);
$stmt->bindParam(':url', $url);
$stmt->bindParam(':count', $count);
$stmt->bindParam(':COMMENT', $comment);

$id = NULL;
$url = $_POST['url']);
$count = 1;
$comment = $_POST['data']);
$stmt->execute();

?>

jquery

$(document).ready(function() {
$('#flagForm').submit(function(){
return false;
});
$('#flag').click(function(){
    $('#comment').show();
});
$('body').on('click', '#commentSubmit', function(e) {
    $.post('flag.php',
    {
        data:$('#comment').val(),
        url:(window.location)
    },
    function(response){
        alert(response);
    });
});
});

html

<div id='comment'><h1 ></h1>
    <form id="flagForm" action="flag.php" method="post">
    <textarea id='commentData' placeholder='whats the problem' ></textarea>
    <input type="submit" id='commentSubmit' />
</form>
</div>

我似乎无法将我的帖子发送到我的php页面。我以前从未遇到过这个问题。目的是让用户标记页面。我有另一个使用相同连接的帖子方法和php页面,所以那不可能是原因。任何帮助都将不胜感激。还有更多关于jquery和html的内容,但这是与问题相关的全部。


首先要检查的是ajax调用是否成功。它返回了500错误吗?200但没有正文吗?根本没有调用过吗?使用大多数浏览器中提供的浏览器调试工具进行检查。如果从未发出调用,则不是php问题-纯粹是jquery / javascript问题。 - bob-the-destroyer
谢谢,我不知道你可以这样做。我会检查的。 - wmurmann
2个回答

2

#comment 是一个div元素,你需要在包含数据的input/textarea上调用.val()方法。

data:$('#commentData').val(),

我看到你在这里遇到了一个非法调用错误:url:(window.location),请改用window.location.hrefwindow.location是一个jQuery无法序列化的对象,因此您会收到该错误。

谢谢,PHP代码中有不必要的“)”符号。但是数据库仍然没有改变。 - wmurmann

1

你的PHP代码有点混乱。不要这样写:

include 'connection.php';
echo "reached page";
$stmt = $conn->prepare("INSERT INTO flagged ( ID,URL,COUNT,comment)VALUES ( :id,    :url, :count,:COMMENT )"); 
$stmt->bindParam(':id', $id);
$stmt->bindParam(':url', $url);
$stmt->bindParam(':count', $count);
$stmt->bindParam(':COMMENT', $comment);

$id = NULL;
$url = $_POST['url']);
$count = 1;
$comment = $_POST['data']);
$stmt->execute();

你应该这样做:
include 'connection.php';

echo "reached page";

$id = NULL;
$url = $_POST['url']);
$count = 1;
$comment = $_POST['data']);

$stmt = $conn->prepare("INSERT INTO flagged ( ID,URL,COUNT,comment)VALUES ( :id,    :url, :count,:COMMENT )"); 
$stmt->bindParam(':id', $id);
$stmt->bindParam(':url', $url);
$stmt->bindParam(':count', $count);
$stmt->bindParam(':COMMENT', $comment);

$stmt->execute();

当然,您也不应该直接将用户输入插入到数据库中,但我假设此时这不是一个真实的应用程序...

谢谢,不用了,我只是想让它能够正常工作,然后再添加检查和清理数据的功能。 - wmurmann
@user1204597,说实话,看到有人在PHP中使用预处理语句,我感到很高兴... :) - Tieson T.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接