I have the following fucntion, which works. I would like to prevent the submission of the form in case that errorMessage.length is greater then 0. I tried with e.preventDefault, nothing, I try return false…nothing. Form is still submitted.
The problem is that you are not determining if there is an error or not until after the ajax call returns which will be long after the default action will have run so trying to prevent the default from that point is too late.
I have the following problem now…if user submit correctly his user name and password, he remain on the submit form…he is not redirected on the login page. In any case, he remain stucked in the login form.
Hi
I have the redirect in php file, named loginCheck. Should I redirect the user from javascript in case that errorMessage is empty? Is that the way how it should work?
Ajax requests are client side so any server redirection won’t have any effect because the page physically hasn’t changed to a new URL, what you will need to do is send back a success/error message and use your JavaScript to run a quick check on the reply back from the server.
In your PHP code you would have something like the below
function loginCheck() {
$return = array(
'status' => false,
'message' => 'You\\'re login attempt has failed!'
);
$isAuthenticated = true;
// Simple login check, this is just an example so you're code will differ
if ($isAuthenticated) {
$return['status'] = true;
$return['message'] = 'You have successfully been logged in!';
}
exit(json_encode($return));
}
Then your JavaScript would look something like this
formLogin.on('submit', function(e) { e.preventDefault();
$.ajax({
type : 'POST',
url : 'loginCheck',
data : $(formLogin).serialize(),
dataType : 'json',
success : function(r) {
if (r.status) {
window.location = 'link-goes-here';
} else {
$('#errorMessageTop').fadeIn();
// You could also use the status message from the response
// alert(r.message);
}
}
});
});