3
I have this JS code that validates, sends and saves the form files in the BD.
I need that after sending and saving in the bd, after Alert, the user is already redirected to another page.
<script>
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
var error = 0;
var serror = 0;
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
if (input.name == "gender") {
if ($('input[name=gender]:checked').length > 0)
data[input.name] = $('input[name=gender]:checked').val();
else {
error++;
if (serror == 0) {
alert('Selecione o sexo');
serror++;
}
}
} else {
if (input.name == "name") {
if (input.value.length >= 3 && input.value != "Nome")
data[input.name] = input.value;
else {
error++;
alert('Nome inválido');
}
} else if (input.name == "email") {
var re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (re.test(input.value))
data[input.name] = input.value;
else {
error++;
alert('E-mail inválido');
}
} else if (input.name == "extra") {
if (input.value.length >= 3 && input.value != "extra")
data[input.name] = input.value;
else {
error++;
alert('Campo inválido');
}
} else if (input.name == "source") {
data[input.name] = input.value;
}
}
}
}
if (error <= 0){
addData(data);
} else {
error = 0;
}
}
function addData(data){
$.ajax({
type: "POST",
url: "...",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader ("", "");
},
success: function (data, status, jqXHR) {
alert("Seu cadastro foi realizado com sucesso!");
form.reset();
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('Houve um erro ao tentar realizar seu cadastro.' + status.code);
}
});
}
</script>
because it does not use: window.location.href = 'linkOuNomeDaPagina" after Alert?
– alan