I am very confused with this code. I try to allow the window to close if all the validations even the call by ajax are correct. The problem is that when I run preventDefault I can't cancel it anymore. In summary, if I click on the save button, if everything is correct, it closes the modal window and if it is not correct, it cancels the closure. Hope you can help me. Thank you
$('#modalAltaReceta').on('hide.bs.modal', function(e){
var cancel = false;
var btn_grabar = false;
$("#grabarReceta").click(function() {
var cantidadSinIngreso = 0;
if($("#inputNombreReceta").val().trim()=="") {
alert("Ingrese un nombre para la receta");
cancel = true;
} else if($("#inputIntroReceta").val().trim()=="") {
alert("Ingrese una introduccion breve");
cancel = true;
} else if($("#inputInstruccionesReceta").val().trim()=="") {
alert("Explique cuales con los pasos para realizar esta receta");
cancel = true;
}
cantidadSinIngreso = 0;
$(".inputIngredientes").each(function(index, item) {
if(item.value.trim() == "")
cantidadSinIngreso++
});
if(cantidadSinIngreso > 0) {
cancel = true;
alert("Ingrese por lo menos un ingrediente");
} else {
$.ajax({
url: 'php/recetas.php',
async: false,
type: 'POST',
dataType: 'json',
data: "tipo_id=grabarReceta&" + $("#frm_nueva_receta").serialize(),
success: function(data) {
if(data['msg'] == 'ok') {
cancel = true;
}
}
});
return cancel;
}
});
if(cancel) {
e.preventDefault();
e.stopImmediatePropagation();
return false;
}
});