Question:
I have a form and in this one I have two INPUTS , these are mandatory so I use the HTML5 REQUIRED property but it only works if I place a BUTTON and it makes my page reload when submitting but I don't send it directly but I use Ajax , and then I want to validate them for that I have used:
<form>
<input type="text" id="dato1" required>
<input type="text" id="dato2" required>
<input type="button" id="boton" value="enviar" onclick="mifuncion()">
</form>
but this does not validate the form with HTML5 using REQUIRED if I use BUTTON the page reloads and I lose the information loaded with AJAX
<button onclick="mifuncion()">Enviar </button>
What I want to achieve is the validation that I have the BUTTON but that the page does not reload
Answer:
Good evening, if what you are looking for is that pressing the button executes your ajax instead of submitting the form, you must override the submit function using ajax:
<script type="text/javascript">
$(document).ready(function () {
$("#boton").submit(function (event) {
// Aqui evitamos que el formulario haga el submit
event.preventDefault();
// Get Asignamos valores para enviarlos mediante ajax:
var posting = $.post('source/login.php', {
user: $("#inputEmail").val(), // valor de input, aqui puedes hacer tus validaciones
pass: $("#inputPassword").val()
});
posting.done(function (data) {
if (data == "Success") { // Respuesta de tu archivo php
window.location.href = "menu.php";
}
else {
alert("El usuario o contrasena es incorrecto");
location.reload();
}
});
});
});
</script>