I'm trying to return a value from PHP to JavaScript through responseText. The idea is if mysqli_num_rows($rslt) != 0, responseText = 1, or if mysqli_num_rows($rslt)= 0, to do an insert and responseText = 0, and then in JavaScript I get the responseText. How can I achieve that, because I tried with echo, but I couldn't find a solution.
JavaScript code:
const request = $.ajax({
url: "Gab.php",
type: "POST",
dataType: 'json',
data: {username: username, password: password,email:email},
success: function(data){
console.log(data);
}
});
request.done(done);
request.fail("Couldnt register the user");
//event.preventDefault();
}}
function done(responseText){
console.log(responseText);
if(responseText == 0){
alert("Successful Registration");
window.location.assign("index.php");
}else{
alert("There is a username or email already registered. Change that USERNAME OR EMAIL!!!");
}
}
PHP code:
//connect to db
include 'debug.php';
$Uusername=$_POST["username"];
$Uemail=$_POST["email"];
$Upassword1=$_POST["password"];
//cleanup for db:
$username = mysqli_real_escape_string($db, $Uusername);
$email = mysqli_real_escape_string($db, $Uemail);
$password_1 = mysqli_real_escape_string($db, $Upassword1);
//check db for existing user or email
$user_check="SELECT Usersusername,Usersemail FROM users WHERE Usersusername = '$username' or Usersemail = '$email'" ;
$rslt = mysqli_query($db,$user_check);
$exist = mysqli_num_rows($rslt);
if(mysqli_num_rows($rslt) != 0){
echo 1;
//$PHPVar = 1;
}else{
$pwd= password_hash($password_1,PASSWORD_DEFAULT);
$result = "INSERT into users(Usersusername,Usersemail,Userspwd) VALUES ('$username','$email','$pwd')";
mysqli_query($db,$result);
echo 0;
//$PHPVar = 0;
}
Perhaps the following might help - I rearranged things a little and corrected the js functions and sent a basic JSON string as the responseText for convenience