I know there are lots of similar questions, but i've been unable to find one that solves my problem.
The thing is i want to check whether the user/password in my form exists against the mysql db, and i do so by calling a javascript function at form's onsubmit attribute that posts the input via AJAX to a php that checks it and echoes result back to the javascript function, which alerts the user and returns false or returns true so that the form submits.
HTML
<span id="error_message" style="color:#CC3300;font-size:15px" ></span><br/>
<form method="post" action="./includes/process_login.php" onsubmit="return validateForm()" name="login_form">
<div>
<label for="email">Email</label><br/>
<input placeholder="Introduce tu email" type="text" id="email" name="email" maxlength="50" />
</div>
<div>
<label for="password">Password</label><br/>
<input placeholder="Introduce tu password" type="password" name="password" id="password" maxlength="16" />
</div>
<div>
<a class="passwordReset" href="./admin/passwordRecovery.php">He olvidado mi contraseña...</a>
</div>
<input type="submit" id="submit_button" value="ENTRAR" />
</form>
JAVASCRIPT/AJAX
function validateForm() {
var pattern = new RegExp(/* Email validation pattern */);
var isValid;
if (pattern.test($("#email").val())) {
$.ajax({
url: "../includes/process_login.php",
cache: false,
type: "POST",
data: "email=" + $("#email").val() + "&password=" + $("#password").val(),
success: function(data){
if (data == '1') {
isValid = true;
} else {
$("#error_message").text('Email/Password incorrectos!CCC');
isValid = false;
}
},
error: function(){
$("#error_message").text('Email/Password incorrectos!');
isValid = false;
}
});
} else {
$("#error_message").text('El email debe tener un formato válido');
isValid = false;
}
return isValid;
}
PHP both validation and form action:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (isset($_POST['email'], $_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if (login($email, $password, $mysqli) == true) {
// Login success
header("Location: ../graficas.php");
echo '1';
} else {
// Login failed
echo '0';
}
} else {
// The correct POST variables were not sent to this page.
echo '0';
}
exit;
The form is ALWAYS submitted when the email input compells to email regex, so the problem must be inside the ajax function. But i can't figure out what it is, and after a few hours, i'm closer than ever to an asylum.
Thanks in advance!