Hi I'm trying to use get data from my database using a PHP function and AJAX. I read that it wasn't really recommendable to use async : false
to get the value so I tried to use callbacks but I can't get the value.
My js/jquery:
$('.inputUsuario').on('keyup change paste blur', function(){
var inputValue = $(this).val();
var msj = "Usuario solo acepta letras y numeros.";
validarUsuario(inputName);
});
function validarUsuario(i){
if(validateUser(i) != 0){
console.log('exists');
} else {
console.log('available');
}
}
function validateUser(i){
var resultado;
userExists(i, function(d){
resultado = d.replace(/\s+/g, '');
console.log("1: "+resultado);
});
console.log("3: "+resultado);
return resultado;
}
function userExists(i, callback){
return $.ajax({
url: "includes/functions/userExists.php",
type: "POST",
data: 'usuario='+i,
success: function(data){
callback(data);
}
});
}
-- I've used replace because the data.responseText comes with a bunch of spaces before the string. --
My PHP:
<?php
require_once('bd_conexion.php');
if(isset($_POST['usuario'])){
$user = $_POST['usuario'];
$user = $conn->real_escape_string($user);
$user = h($user);
try{
$stmt = $conn->prepare('SELECT COUNT(*) FROM `usuarios` WHERE usuario = ?;');
$stmt->bind_param('s', $user);
$stmt->bind_result($num);
$stmt->execute();
while($stmt->fetch()){
echo $num;
}
$stmt->close();
$conn->close();
} catch (Exception $e){
echo $e->getMessage();
}
}
function h($s){
return htmlentities(htmlspecialchars($s, ENT_QUOTES, 'utf-8'), ENT_QUOTES);
}
?>
-- I've checked that the query works and it is giving me back the value that I need but it doesn't go out of the AJAX --
PD: I've read lots of posts and the documentation that the people that answered suggested. That's how I got to callbacks. However I can't make my callback work.
Thank you all for your answers!