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);
});
});
});
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?
@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.
@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.