将数据保存到MySQL并使用该数据更新页面而无需刷新


Save data to MySQL and update page with that data without refresh

我试图将数据从评论表单保存到MySQL数据库中,然后用该评论更新页面,而无需用户刷新。类似于Facebook评论的工作原理。

我到处寻找这个问题的答案,但我还没有找到一个适合我需要的。

下面是将表单数据提交给php脚本的AJAX:
var ajaxSubmit = function(formEl) {
    // fetch where we want to submit the form to
    var url = $(formEl).attr('action');
    // fetch the data for the form
    var data = $(formEl).serializeArray();
    // setup the ajax request
    $.ajax({
        url: url,
        data: data,
        dataType: 'json',
        success: function(data) {
            if(rsp.success) {
                alert("Comment Successfully Added!");
        }
    });
  return false;
}

我知道这个页面目前不会更新这个脚本,因为我正在调用一个警报。但是,当我提交数据时,我被带到/ajax/comment.process.php页面,这是调用insertComment()函数并将评论插入数据库的页面。我现在在success()函数中有alert()函数,我甚至没有得到它。

我想要的是当评论被提交时,用户不离开当前页面,它只是更新他们刚刚提交的内容。

/ajax/comment.process.php'

中的代码
    session_start();
include_once('../classes/comment.class.php');
include_once('../classes/db.class.php');
$user_id = $_SESSION['user_id'];
$db = new DBConnection;
$comments = new Comment($db);
$blog_id = intval($_POST['blogID']);
$addCom = $comments->addComment($user_id);
if($addCom === FALSE) {
    $resp = "<span class='error'>Error adding comment</span>";
} else {
    $resp = $comments->getComments($blog_id);
}
return $resp;

该脚本调用insertComment()函数将评论保存到数据库中,然后如果返回true,则调用getComments()函数检索该特定帖子的评论并将其存储在数组中。

评论成功保存到数据库,但我被重定向到空白的ajax/comment.process.php页面。我如何用他们发布的评论更新当前页面而无需刷新页面?我认为返回$resp变量会做到这一点,然后我可以做一个foreach()循环来显示它们,但显然不是这样。

EDIT:我已经实现了下面答案中建议的一切,我仍然没有解决这个问题。表单仍然被提交到/ajax/comment.process.php,即使我有这三个应该阻止表单被提交的东西:preventDefault();, return false;return ajaxSubmit(this);

在ajax中,您可以删除dataType: 'json',和删除if(rsp.success) {,并制作一个简单的警报

$.ajax({
        url: url,
        data: data,
        success: function(data) {
                alert("Comment Successfully Added!");
                alert(data);
        }
});

在php中,使用echo

代替你正在使用的返回值
echo $resp;

至少你会看到是否有错误

之后,你可以开始使用json代码

在php

echo json_encode($resp);//as soon as $resp is an array

在ajax中你可以像这样发出警告alert(data.keyofthearray)

要防止表单提交(这是正在发生的事情),使用onsubmit="return ajaxSubmit(this);"

也有一个语法错误在您的ajax代码。您从未关闭if

var data = $(formEl).serialize();
$.ajax({
    url: url,
    data: data,
    dataType: 'json',
    success: function(data) {
        if(data.success) {
            alert("Comment Successfully Added!");
        }
    }
});