Reputation: 1450
I have login form with submit button which calls Javascript function, in that function I call PHP file with AJAX. On PHP side I check if username, email and password are correct and then I return results to div with class Result. I need to return PHP check result and make further actions in javascript, my code:
PHP:
if (isset($_POST['username_or_email']) && isset($_POST['password'])) {
$username_or_email = mysqli_real_escape_string($conn, $_POST['username_or_email']);
$password_post = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "SELECT `password` FROM `users` WHERE `username` = '".$username_or_email."' OR `email` = '".$username_or_email."' LIMIT 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
/* Check if username or email exists */
if (mysqli_num_rows($result) > 0) {
echo "valid_user";
} else {
echo "invalid_user";
}
/* Check if password is correct */
if (password_verify($password_post, $row['password'])) {
echo 'valid_pass';
} else {
echo 'invalid_pass';
}
$conn->close();
}
JQUERY:
success: function (data) {
if (data == "invalid_user") {
$(".result").fadeIn(500).html("Incorrect username or email.");
}
if (data == "invalid_pass") {
$(".result").fadeIn(500).html("Incorrect password.");
}
if (data == "valid_pass") {
$(".result").fadeIn(500).html("Success, redirecting to account.");
setTimeout(function() {
document.location.href = 'nextpage.php';
}, 2500);
}
}
So my questionis: how to make check on JQUERY side properly if I have several IF statements on PHP side. After user press login button I want to show that username or pass is correct/incorrect and which one is correct/incorrect, it is needed just for information purpose.
Upvotes: 3
Views: 1474
Reputation: 71
The best way is to create an array of elements in your PHP file and store all the information you need. For example:
$info=array("user"=>"valid","password"=>"invalid");
Then, convert the array into a JSON string and simply echo it:
echo json_encode($info);
Once the data is retrieved, you can easily manipulate them by converting them into a javascript array of elements like this:
info=JSON.parse(data);
NOTE: PHP can only "communicate" with Javascript via Strings. JSON Strings is the most commonly used way of achieving such results, due to it's simplicity.
Upvotes: 1