Solution 1 :

There is a syntax error in your code. In the code $.ajax . function is missing.

$(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);
          });
        });
      });

Problem :

I’m using a JQuery AJAX Call and want to prevent normal PHP form submission. Here’s my form element:

<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 Call:

    $(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);

        });

});

Upon clicking the submit button, the browser is still being redirected to “include/ajax_add_to_cart.php”, why isn’t event.preventDefault(); preventing the default form submission?

Comments

Comment posted by $.ajax

jquery

Comment posted by Adam

@prasanth The AJAX call is working, the php form calls an insert to the database, data is being inserted properly. Just dealing with the redirect problem.

Comment posted by jsfiddle.net/pn5rwojh

its working normal

Comment posted by Adam

@prasanth – I believe I couldn’t see any errors in the console if there are errors because I’m being redirected to the ajax_add_to_cart.php page. I don’t see any errors in the console.

Comment posted by Ritesh Khandekar

Try with

By