2

Possible Duplicate:
jQuery: Return data after ajax call success
jQuery AJAX: return value on success

I can't figure out why goodPassword always returns undefined I"m sure it's just a dumb mistake and will appreciate your answer

function foo(){
    var goodPassword;
    jQuery.ajax({
        data: "action=Potato",
        url: 'servletPotato',
        timeout: 2000,
        error: function() {
            console.log("Failed to send ajax");
        },
        success: function(r) {
            var data = jQuery.parseJSON(r);
            if(data.aprovePassword == "true")
            {
                goodPassword = true;
            }
            else
            {
                goodPassword = false;
            }
        }
    });
    return goodPassword;
}

the ajax call is definitely working and data.aprovePassword definitely return from the servlet as "false"

Community
  • 1
  • 1

3 Answers3

2

Because goodPassword hasn't been assigned anything yet, since the XHR request executes after the function ends and that's why by the end of the function, nothing has been assigned. An alternative function would be:

function foo(successCallback) {
    var goodPassword;
     jQuery.ajax({
         data: "action=Potato",
         url: 'servletPotato',
         timeout: 2000,
         error: function() {
            console.log("Failed to send ajax");
         },
         success: function(r) {
            var data = jQuery.parseJSON(r);
            if(data.aprovePassword == "true")
                {
                    goodPassword = true;
                }
            else
                {
                    goodPassword = false;
                }
            successCallback(goodPassword);
       }});
  }
Some Guy
  • 15,854
  • 10
  • 58
  • 67
  • Since javascript is single-threaded, it does not matter how long the request takes. foo will always return before the callback is invoked. – Jonas Høgh Aug 18 '12 at 14:20
  • @JonasH Sure? With it being single threaded, if the request completes fast enough, it should fire the event before the function ends. Except for in jQuery, we don't really know what's going on behind the scenes. – Some Guy Aug 18 '12 at 14:24
  • functions are never preempted in the middle of execution in JS. The XHR completion event will simply be added to the queue of events waiting to execute once the current code completes. Jquery doesn't change this, it just adds a thin abstraction layer on top of XHR to shield users from browser incompatibilities – Jonas Høgh Aug 18 '12 at 14:36
1

The problem is that ajax requests are asynchronous, so the function is returning immediately after kicking off the jQuery.ajax call, and at that point goodPassword is still undefined.

Instead you need to do something like this:

function foo(callback) {
    var goodPassword;

    jQuery.ajax({
     data: "action=Potato",
     url: 'servletPotato',
     timeout: 2000,
     error: function() {
        console.log("Failed to send ajax");
     },
     success: function(r) {
        var data = jQuery.parseJSON(r);

        if(data.aprovePassword == "true") {
                goodPassword = true;
        } else {
                goodPassword = false;
        }

        callback(goodPassword);
   }});
}

You would then call the function like this:

foo(function(goodPassword) {
    console.log('goodPassword is ' + goodPassword);
});
0

You can't check the return value as the ajax call occurs after the function returns.

To perform two actions one on success and one on failure you need to do the following:-

var foo = function(goodCallback, badCallback){
  jQuery.ajax({
    data: "action=Potato",
    url: 'servletPotato',
    timeout: 2000,
    error: function() {
      console.log("Failed to send ajax");
    },
    success: function(r) {
      var data = jQuery.parseJSON(r);
      if(data.aprovePassword == "true")
      {
        goodCallback();
      }
      else
      {
        badCallback();
      }
    }
  });
};

foo(
  function() {
    console.log('dude good password');
  },
  function() {
    console.log('bad password');
  }
);

or Have only 1 callback function takes the boolean value of goodpassword...

James Kyburz
  • 13,775
  • 1
  • 32
  • 33