jQuery AJAX Call - event.preventDefault (); не останавливая PHP отправку формы в любом браузере - PullRequest
0 голосов
/ 19 января 2020

Я использую JQuery AJAX Call и хочу запретить обычную 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 (); запретить отправку формы по умолчанию?

1 Ответ

1 голос
/ 19 января 2020

В вашем коде есть синтаксическая ошибка. В коде $.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);
          });
        });
      });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...