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

标签 php javascript mysql ajax jquery

我正在尝试将评论表单中的数据保存到 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() 函数检索评论对于该特定帖子并将它们存储在一个数组中。

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

编辑:我已经实现了下面答案中建议的所有内容,但尚未解决此问题。即使我有以下三件事应该阻止表单提交:preventDefault();,表单仍然被提交到 /ajax/comment.process.phpreturn 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)

关于php - 将数据保存到 MySQL 并使用该数据更新页面而无需刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15235523/

相关文章:

javascript - 错误 : Uncaught TypeError: Cannot set property 'onclick' of null

php - 生成 HTML 以显示具有正确类型(文本、复选框等)的自定义问题并正确添加所需的属性

javascript - Tabbable DIV 上的空格键或 Enter 键 : Some browsers don't intercept Keypress

javascript - Chrome 上的 XML 错误但在 FF 上没问题?

php - Opencart 产品总价乘以定制选项

php - YouTube API videoEntry计数评论

php - 通过 ODBC Sybase "PARAM datastream"错误的 PDO 准备语句

javascript - 我想使用 javascript 单击网站上的所有 div 框

php - 执行查询以将数据从一个表复制到另一个表

php - 将循环的 MySQL 数组存储为字符串变量