【问题标题】:Ajax success response not displaying echo message from PHP codeAjax 成功响应不显示来自 PHP 代码的回显消息
【发布时间】:2020-12-04 15:39:30
【问题描述】:

我正在尝试在我的 PHP 项目中开发“添加到购物车”功能。这是代码。

这是我从中获取产品数据的表单。

表格

<form class="product-form" method="POST">
                        <input name="product_id" type="hidden"
                            value="<?=$data['id']?>">
                        <input name="user_id" type="hidden" value="1">
                        <button name="trending-submit" type="submit" class="btn btn-success">Add To
                            Cart</button>
                    </form>

ajax

$(".product-form").submit(function () {
    var form_data = $(this).serialize();
    var button_content = $(this).find("button[type=submit]");
    button_content.html("Adding...");
    $.ajax({
      url: "./includes/add-to-cart.php",
      type: "POST",
      data: form_data,
      dataType: "html",
      success: function (response) {
        alert(response);
        $(".cart-quantity").html(response);
        button_content.html("Add to Cart");
      },
    });
    return false;
  });

“警报(响应)”根本不显示任何内容。

调用购物车对象函数的 PHP 代码。

PHP

    <?php
ob_start();


require("classes/Database.php");
$db = new Database();

require("classes/Cart.php");
$cart = new Cart($db);


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ($_POST['product_id'] != null && $_POST['user_id'] != null) {
        $cart->addToCart($_POST['product_id'], $_POST['user_id']);
    }

    $total = $cart->showCartQuantity();
    echo $total;
    exit;
}

【问题讨论】:

  • 旁注:检查$_POST 索引与null 是不够的(它仍然会产生“未定义索引”通知)。请改用isset()
  • 当您创建网店时,我怀疑您是否也希望将空的产品 ID/ID 添加到您的购物车中;使用empty()

标签: php mysql ajax


【解决方案1】:

您不能将相对路径与$.ajax() 一起使用。您应该改用您要发布数据的 URL(包括 FQDN)。

在浏览器中检查您的网络选项卡,并找到 XHR 请求以获取更多信息。

另外,您应该添加e.preventDefault() 以防止HTML &lt;form&gt; 的默认行为,即刷新页面(即将浏览器位置更改为HTML &lt;form&gt; 的@987654325 中指定的URL @ 属性)。

$(".product-form").submit(function (e) {
    e.preventDefault();

    var form_data = $(this).serialize();
    var button_content = $(this).find("button[type=submit]");
    button_content.html("Adding...");

    $.ajax({
        url: "http://localhost/ajaxfile.php", // Full URL of PHP file
        type: "POST",
        data: form_data,
        dataType: "html",
        success: function (response) {
        alert(response);
        $(".cart-quantity").html(response);
        button_content.html("Add to Cart");
        },
    });

    return false;
});

【讨论】:

  • 这修复了它!谢谢你^^
猜你喜欢
  • 2015-04-26
  • 2022-01-09
  • 1970-01-01
  • 2019-02-20
  • 2016-12-27
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2016-04-01
相关资源
最近更新 更多