0

I have a code that checks if a user exists in my database through an xmlhttprequest in this case. For some reason when I tell it to return true, I get undefined. I have no idea what the problem could be here. The function exists in an object window._ also _.xhr() just basically creates an xmlhttprequest and is very similar to jquery's $.ajax method.

vu: function(u,c){
    if(typeof c==="undefined"){
        c=null;
    }
    if(c!==""&&c!==null){
        alert(c); //when alert is executed here the result is a string "true" as it should be. Since kiddo is an user in my database
        if(c=="true"){
            return true;
        }
        return false;
    }
    _.xhr({
        method:"get",
        adress:"../php/include/functions.php?function=user_exists&a="+u,
        asyn:true,
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        ready:function(e){
            alert(e)
            _.vu.call(_.vu,u,e); //<-- This is a callback.
        }});
    }
Somebody
  • 333
  • 3
  • 12
  • 2
    You can not return from an asynchronous method. It is like ordering a delivery pizza and trying to eat it as soon as you hang up the phone. Not going to happen. – epascarello Feb 23 '16 at 20:32
  • Your callback will only return a value into the context of the `ready` handler. It won't return that value to the point where `_.vu(...)` was called in the first place. – csum Feb 23 '16 at 20:45
  • But, Shouldn't this `_.vu.call(_.vu,u,e);` call the function again with the variable c set to the request responseText? (e is the responseText) Since I am able to access the response outside the ready handler when the callback is executed. – Somebody Feb 23 '16 at 20:54
  • So, The real problem here seems to be that when I'm doing the `if(typeof c!=="undefined"){//do this}` it just doesn't work and executes everything inside the statement anyways, although the c variable is undefined. – Somebody Feb 23 '16 at 21:07
  • `_.vu.call(_.vu,u,e);` does indeed call the function again, but since the method is asynchronous it is unable to simply return the value to the original caller. Take a look at the similar question, [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – csum Feb 23 '16 at 21:29

0 Answers0