Tommy Tommy - 1 month ago 18
PHP Question

Ajax returns with PHP

Alright so I am trying to put this thing together but I do not understand what is the problem with this code. I am basically trying to return false incase name exists in the database but no matter what ajax will just pass it as a "success"

Here is the code

Running the

function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
return true;
},
error:function(data) {
return false;
}
});
}


The code is executed perfectly and it actually passed all the things it needs, and the PHP function does get called.
PHP function bellow.

public function nameExists($name) {
$handler = new sql();
$sql = $handler->connect();

$sql->real_escape_string($name);
$name_final = ucfirst($name);

$result = $sql->query("SELECT ime FROM users WHERE ime='".$name_final."'");



if($result->num_rows != 0) return true;
else {
$handler->log_write($name, "login_fail","NULL");
return false;
}
$sql->close();
return false;
}


Now the problem is success and the error. No matter what it will alwys be success. It doesnt like pay attention at when I return FALSE from the PHP at all and such.

Answer

AJAX calls are literally just an HTTP request, like any other HTTP request. You're not directly "executing" PHP code when you make an ajax call, you're doing an HTTP request to the server, which (eventually) executes a PHP script on your behalf.

That means any return from the PHP code are completely invisible to Javascript.

Only OUTPUT from PHP will ever be seen by Javascript, which means you need to echo that data, not return it.

And note that any HTTP response from PHP is also literally plain text. Any output you perform in PHP will be converted to text, which means that boolean false you're trying return will be converted to the string equivalent of a boolean false - an invisible zero-length string.