I want to validate a form with ajax, how could I validate the beforeSend : function(xhr, opts) to continue with success: function (data) , as you can see in that first part I am requiring the data of the inputs if they are empty, I feel like I'm pretty close but there are a few things that I can't get to work quite right. My form is not being sent to the destination email, my php file is correct.
$(document).ready(function () {
var frm = $('#formulario');
frm.submit(function (e) {
e.preventDefault();
console.log(frm.serialize());
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: new FormData(this),
processData: false,
contentType: false,
beforeSend : function(xhr, opts) {
if (document.getElementById('nombre').value != "" ||
document.getElementById('dni').value != "" ||
document.getElementById('correo').value != "" ||
document.getElementById('telefono').value != "" ||
document.getElementById('fecha').value != "" ||
document.getElementById('lugar').value != "" ||
document.getElementById('relacion').value != "" ||
document.getElementById('detalle').value != "" ||
document.getElementById('archivo[]').value != "" ) {
frm.addClass('was-validated');
console.log("abort");
xhr.abort();
}
},
success: function (data) {
var div = document.createElement('div');
div.appendChild(document.createTextNode("La denuncia fue enviada con éxito"));
div.classList.add('alert', 'alert-success', 'mt-4', 'text-center');
document.querySelector('form').appendChild(div);
setTimeout(function() {
document.querySelector('.alert').remove();
}, 5000);
document.querySelector('form').reset();
},
error: function (data) {
var div = document.createElement('div');
div.appendChild(document.createTextNode("¡La denuncia no pudo ser enviada, por favor intente nuevamente!"));
div.classList.add('alert', 'alert-danger', 'mt-4', 'text-center');
document.querySelector('form').appendChild(div);
setTimeout(function() {
document.querySelector('.alert').remove();
}, 5000);
},
});
});
});