1

I am having a problem here, if I have a data verification. More of the function $ ajax jquery not return value of true and false, know how I can fix this?

Example code:

function ret(as){
    ....codes...
     $.ajax({
        type: "POST",
        url: "../../03",
        data: "as="+as,
        success: function (msg) {
          if(msg == 'true' ){
           ..codes..
           return true;  
          }else{
           ..codes..
           return false;
          }
        } 
    });
  }

Example call:

var check= ret("user");

if(check== true){
  ..run ..
}
Community
  • 1
  • 1
user628298
  • 287
  • 2
  • 14
  • Solid answers to a very similar question http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery – gnarf Oct 21 '11 at 03:44

3 Answers3

2

By default ajax calls are asynchronous - that's actually what the 'A' stands for. This means that the your ret function will return before the success function is ever invoked. You have two options for fixing your issue:

  1. Make your ajax call synchronous - see the async options at http://api.jquery.com/jQuery.ajax/. This is almost always a bad idea, because the entire page will block until the call returns
  2. Invert your control flow so that the desired behavior happens when the success callback is invoked. You can do this by passing a function into ret:

    function(as, successHandler) { ...

    success: function(msg) {
        successHandler(msg == 'true');
    }
    
tilleryj
  • 14,259
  • 3
  • 23
  • 22
1

The user wants to transmit the true/false response outside the jQuery object, so that the function can return it. There are situations were you really need the function to return something and not invoke a callback.

Even if the jQuery call is synchronous (i.e. 'async: false'), the example code above would not work, but it's true that your call must be explicitly specified as synchronous.

The correct way to do is to attach your jQuery object to a variable:

var obj = jQuery.ajax({ 'async:false', (...)

Then, at the end of your function, after the jQuery object closing parenthesis, add to your function:

return obj.responseText;
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
lol
  • 11
  • 1
0

Ajax is asynchronous. You cannot you use a return value. You must use a callback:

ret("user", function(check) {
  if (check == true)
    .. run ..
});

And you can implement ret like this:

function ret(as, callback) {
  ....codes...
   $.ajax({
      type: "POST",
      url: "../../03",
      data: "as="+as,
      success: function (msg) {
        if(msg == 'true' ){
         ..codes..
         callback(true);
        }else{
         ..codes..
         callback(false);
        }
      } 
  });
}

Another option would be to force the request to be synchronous, but that's not really the idiomatic way of doing it.

Jakob
  • 24,154
  • 8
  • 46
  • 57