Rheedwahn Rheedwahn - 1 month ago 4
Ajax Question

Javascript, Php, Ajax

i have a problem with this my script.

$("#login").click(function(event) {

event.preventDefault();

var email = $("#email").val();
var pass = $("#password").val();

$.ajax({

url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){

if(data == "1"){

alert(data);
}

}

})


i want it to alert a value i am getting from an echo in another php file

<?php

if(isset($_POST['userLogin'])){

$email = mysqli_real_escape_string($con, $_POST['userEmail']);

$password = md5($_POST['userPassword']);

$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";

$query_login = mysqli_query($con, $sql_login);

$count_login = mysqli_num_rows($query_login);

if($count_login == 1){

$row_login = mysqli_fetch_assoc($query_login);

$_SESSION['uid'] = $row_login['user_id'];

$_SESSION['name'] = $row_login['first_name'];

echo "1";

}


}

?>


if i didnt put the alert(data) in an if condition, it displays the value i echo, but i need the condition to enable the right user logged in

Answer

What can IF can also ELSE.

In your ajax add the else conditions to see if it helps uncover the issue:

if (data == "1") {
  alert('youre in');
} else {
  alert('try again');
}

And in your php, also account for the else condition (and do strict checking on that count of rows with ===):

if ($count_login === 1) {
  // code ...
  echo '1';
} else {
  echo 'Sorry, the login is incorrect';
}