Im trying to get data from my php file using success function(data)
When im using console.log(data) i get; true/false/exists But i cant make a if statement, if i do it dosent alert!!
Heres my js file
function ajaxCall(username, email, password){
$.ajax({
type: 'POST',
url: '../register.php',
data: {
'username' : username,
'email' : email,
'password' : password,
},
success: function(data) {
if(data === "exists")
alert("user exists");
}
});
}
heres my .php file
<?php
$servername = "#";
$username = "#";
$password = "#";
$dbname = "#";
$regusername = $_POST['username'];
$email = $_POST['email'];
$regpassword = $_POST['password'];
$mysqli = new mysqli($servername, $username, $password, $dbname);
$selectQuery = "SELECT username FROM users WHERE username = '$regusername'";
$select = $mysqli->query($selectQuery);
// var_dump($select->num_rows);
if( $select->num_rows == 0) {
$insertQuery = "INSERT INTO users (username, password, email) VALUES ('$regusername','$regpassword','$email');";
$insert = $mysqli->query($insertQuery);
if( $insert == true) {
echo "true";
}else {
echo "false";
}
}else {
echo "exists";
}
?>
Use a properly structured data format, such as json:
php:
$data=['exists'=>false];
if( $select->num_rows == 0) {
$insertQuery = "INSERT INTO users (username, password, email) VALUES ('$regusername','$regpassword','$email');";
$data['inserted'] = (bool) $mysqli->query($insertQuery);
}else {
$data['exists']=true;
}
header('Content-Type: application/json');
echo json_encode($data);
die();
JS
$.ajax({
type: 'POST',
url: '../register.php',
data: {
'username' : username,
'email' : email,
'password' : password,
},
success: function(data) {
if(data.exists){
alert("user exists");
}elseif(data.inserted){
alert("inserted");
}else{
alert("did not insert");
}
});
if(data == "exists") instead of if(data === "exists")
Chances are there is extra whitespace in the response
Try:
if($.trim(data) === "exists")
You are not responding with an answer to the front, you just echoing 'exist' word in your php handler. Try using json_encode
, because the dataType is "json" by default not "html"
Lets's say
if($insert) {
$response['exist_status'] = 'exist'
}else{
$response['exist_status'] = 'do not exist'
}
echo json_encode($response);
In your jquery
success: function(response) {
if(response.exist_status && response.exist_status == 'exist') {
alert(1);
}
}
I think its better to work with HTTP-Status codes like 404 or 403 (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) instead of retuning a string. This can by done with PHP (http://php.net/manual/de/function.http-response-code.php) and use the error callback of your ajax call (http://api.jquery.com/jquery.ajax/ --> StatusCode)