I've been working with JavaScript and jQuery for a while, and wanting to carry out a fairly simple functionality, I have run into a small problem (specifically related to promises)
I intend to use the SweetAlert2 library to ask the user, if they are sure they want to send the form, there is a related question but please read it first before marking duplicate, since the doubts are not different.
I am using the submit
jQuery event, to, with swal2, ask the user, I do it in the following way:
$('#formulario').on('submit',
() => {
const url = '@Url.Action("ValidarRefrigeracionDeCuba")';
const codigoDelfos = $('#@Html.IdFor(x => x.CodigoDelfos)').val();
$.get(url, { codigoDelfos: codigoDelfos }, (result, status) => {
if(result.Objeto == true)
return Swal.fire({
title: '¡Advertencia!',
text: "¡El transformador no tiene cargada ninguna refrigeración de cuba en Delfos!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Continuar de todas formas'
}).then((result) => {
return result.value === true;
});
});
});
But the form (logically) is submitted before the promise is resolved.
I tried to do it using async/await, but was unsuccessful, as the form, too, was always submitted.
What is the solution to this problem?
Basically what I was telling you was to do the
preventDefault()
delevent
and then force thesubmit
throughJS
.submit
I do it by because it doesn't trigger theJS
document.getElementById("formulario").submit();
events. If I did it withjQuery
doing the$(this).submit();
or$("#formulario").submit();
, the event would be launched again -> the event would be canceled -> it would be called again... And so on in a loop.I suppose that the validations you mention will be done anyway.
I leave you this snippet :