I am creating an online store as a school project in Laravel. Everything is fine until I want to prevent a button from executing its "submit" action.
{!! Form::open(['url' => '/in_cursos_carts', 'method' => 'POST', 'class' => "addtocart inline-block" ]) !!}
<input type="hidden" name="curso_id" value="{{$curso->id}}">
<input type="submit" value="Agregar al carrito" class="btn btn-info">
{!! Form::close() !!}
That is the code of the Form that I want to "condition with AJAX. And this is the AJAX code that I want to execute so that the submit is executed.
$('.addtocart').on("submit", function(ev)
{
ev.preventDefault();
var $form = $(this);
var $button = $form.find("[type='submit']");
$.ajax(
{
url: $form.attr("action"),
method: $form.attr("method"),
data: $form.serialize(),
beforeSend: function()
{
$button.val("Cargando...");
},
success: function()
{
$button.css("background-color", "#00c853").val("Agregado");
},
error: function()
{
console.log(err);
$button.css("background-color", "d50000").val("Hubo un error.");
setTimeout(function(){
restartButton($button);
}, 5000);
},
});
return false;
});
function restartButton($button)
{
$button.val("Agregar al Carrito").attr("style", "");
};
The idea is that from the view where the products appear the user can add the product to the shopping cart without having to go to the screen where the user will pay but apparently the ev.preventDefault (); It is not running.