Reputation: 33
I am trying to submit a form that validates, and than logs in the user in PHP. I return false when there is an error, but it does not stop the form from submitting. How can I prevent the form from submitting only when there is an error? I put a return false
at the bottom but that stopped the whole form from submitting, even if the login was good.
login.js
$('#login_form').submit(function(e) {
if (validate({required: "email, password"}) == true) {
return attemptLogin();
} else {
return false;
}
});
function attemptLogin() {
var email = $("#email").val();
var password = $("#password").val();
var json = "JSON";
$.ajax({
url: "/login",
type: "POST",
data: {
email: email,
password: password,
json: json
},
success: function (data) {
data = JSON.parse(data);
if (data['message'] != 'undefined') {
if (data['message'] != 'success') {
$('#errors').html(data['message']);
return false;
}
}
}
});
}
and my PHP
if ($validation === true) {
$user->findByEmail($_POST['email'], array('first_name', 'password', 'id'));
if (!$user->login($_POST['password'], $user->password, $user->id)) {
if (isset($_POST['json'])) {
echo json_encode(array('message' => 'Invalid email or password.'));
die;
} else {
$redirect->to('/login', '<div class="message message-error">Invalid email or password.</div>');
}
} else {
echo json_encode(array('message' => 'success'));
//die;
$redirect->to('/home', '<div class="message message-success">Hi ' . $user->first_name . ', you have been logged in!</div>');
}
Upvotes: 0
Views: 1990
Reputation: 178
You can use e.preventDefault()
- it will prevent any default browser events;
$('#login_form').submit(function(e) {
e.preventDefault();
if (validate({required: "email, password"}) == true) attemptLogin();
});
Upvotes: 2
Reputation: 3305
The return false only in if statement. I would like to store a flag that you can return from success function(data). Try this,
success: function (data) {
data = JSON.parse(data);
var flag = true;
if (data['message'] != 'undefined') {
if (data['message'] != 'success') {
$('#errors').html(data['message']);
flag = false;
return flag;
}
}
return flag;
}
Upvotes: 0