The way to make a request without reloading the whole page is to use AJAX
There is the form with pure javascript with XMLHttpRequest
or at my very personal opinion the most simple that is using $.ajax()
in this way
var request = $.ajax({
dataType: 'json',
method: 'POST',
url: '/path/a/tu-url.php',
data: $( "form" ).serialize()
});
//Manejo cuando la petición termina
request.done(function( event ) {
// Aquí puedes redirigir si no hay fallos
});
//Manejo cuando la petición falla
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
Or even simpler with $ .post () in this way
$.post( "/path/a/tu-url.php", $( "form" ).serialize());
Here is a functional example of how an AJAX execution of a form works
$('form').submit(function(e) {
e.preventDefault()
$('.invalid-helper').remove();
var validates = true;
var $inputs = $(this).children('input');
$.each($inputs, function() {
// Revisamos que los campos no estén vacíos
if ($(this).val() === '') {
validates = false;
$(this).after('<span class="invalid-helper">El campo no puede estar vacío</span>');
}
});
if (!validates) {
return;
}
$.post(
"https://hookb.in/vaP3LY5a",
$("form").serialize()
).done(function() {
console.log('Éxito');
})
.fail(function() {
console.log('Falló');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form" action="https://requestb.in/y6crnty6" method="post">
<input type="text" name="input_1">
<br/>
<input type="text" name="input_1">
<br/>
<input type="text" name="input_1">
<br/>
<button type="submit">Enviar</button>
</form>
I hope I have been helpful, if you do not leave me a comment:)