【问题标题】:jQuery AJAX Call - event.preventDefault(); not stopping PHP form submission in any browserjQuery AJAX 调用 - event.preventDefault();不停止任何浏览器中的 PHP 表单提交
【发布时间】:2020-01-19 14:52:56
【问题描述】:

我正在使用 JQuery AJAX 调用并希望阻止正常的 PHP 表单提交。这是我的表单元素:

<form action="include/ajax_add_to_cart.php" method="get" id="form_add_to_cart">

<!-- fields unimportant for example -->

<button type="submit" name="add" class="btn" id="single_product_add_to_cart">Add to cart</button>

</form>

jQuery Ajax 调用:

    $(document).ready(function() {

    $("#form_add_to_cart").submit(function(event) {

        //Stop the form from submitting normally and refreshing the page
        event.preventDefault();

        //get the form data
        var formData = {
            'product_id' : $('input[name=product_id]').val(),
            'quantity' : $('input[name=quantity]').val()
        }

        //process the form
        type : "GET",
        url : "ajax_add_to_cart.php",
        data : formData,
        dataType : "json",
        encode : true
}).done(function(data) {

            //log data to console
            console.log(data);

        });

});

点击提交按钮后,浏览器仍然被重定向到“include/ajax_add_to_cart.php”,为什么不是event.preventDefault();阻止默认表单提交?

【问题讨论】:

  • jquery $.ajax 语法错误或检查您的 console.log 是否有任何错误?
  • @prasanth AJAX 调用正常,php 表单调用插入数据库,数据被正确插入。只是处理重定向问题。
  • 它工作正常jsfiddle.net/pn5rwojh。你的控制台有什么错误吗?
  • @prasanth - 如果有错误,我相信我在控制台中看不到任何错误,因为我被重定向到 ajax_add_to_cart.php 页面。我在控制台中没有看到任何错误。
  • 试试return false;

标签: javascript php jquery html ajax


【解决方案1】:

您的代码中存在语法错误。在代码$.ajax 中。功能缺失。

$(document).ready(function() {
        $("#form_add_to_cart").submit(function(event) {
          //Stop the form from submitting normally and refreshing the page
          event.preventDefault();

          //get the form data
          var formData = {
            product_id: $("input[name=product_id]").val(),
            quantity: $("input[name=quantity]").val()
          };
          $.ajax({
            type: "GET",
            url: "ajax_add_to_cart.php",
            data: formData,
            dataType: "json",
            encode: true
          }).done(function(data) {
            //log data to console
            console.log(data);
          });
        });
      });

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2013-12-28
    相关资源
    最近更新 更多