1

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!

Diego Rios
  • 463
  • 1
  • 5
  • 18
  • are you expecting `validateUser` will return something? it doesn't. Also, the console.log('3.') will result in undefined, but the other two should be ok - though, why you are using a callback **and** `.done` is odd - the `.done` should be enough – Jaromanda X Jun 18 '17 at 06:52
  • 1
    You might find https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 helpful – Professor Abronsius Jun 18 '17 at 06:52
  • 1
    also, the `return resultado;` inside your callback is meaningless – Jaromanda X Jun 18 '17 at 06:53
  • @JaromandaX That `validateUser` function is kind of messy because i've been playing with the options. Even if I put the return outside of the `.done` or the callback, it returns `undefined`. – Diego Rios Jun 18 '17 at 06:53
  • @RamRaider I already read that. It's really helpful but I can't really make my code work after reading that. – Diego Rios Jun 18 '17 at 06:56
  • 1
    yes, validateUser returns undefined because you don't return anything from validateUser - and you can't return anything meaningful because ajax calls are asynchronous - callback is one method to use asyncrhonous code, you just are not doing it right - you don't even show how validateUser is being used – Jaromanda X Jun 18 '17 at 06:56
  • Please add the console output to your question. – hakre Jun 18 '17 at 06:59
  • 2
    I would suggest taking a look at `Promises` - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises – Professor Abronsius Jun 18 '17 at 07:01
  • @RamRaider i'll do that, thanks! – Diego Rios Jun 18 '17 at 07:03

0 Answers0