11
   function ajaxRefresh(actionUrl) {
        $.ajax({
        url: actionUrl,
        success: function() {
             return true;
        }});
        return false;
    }

The function anyway returns false even when a request is succeeded, becouse the request is asynchronous. How I can return true when request is succeeded?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Artur Keyan
  • 7,643
  • 12
  • 52
  • 65
  • It may help solve this problem: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/57968689#57968689 – Sajad Mirzaei Sep 17 '19 at 06:49

6 Answers6

19

You should set parameter async to false. Try this code:

function ajaxRefresh(actionUrl) {
    var succeed = false;

    $.ajax({
    async: false,
    url: actionUrl,
    success: function() {
         succeed = true;
    }});

    return succeed;
}
Pavel Surmenok
  • 4,584
  • 4
  • 30
  • 33
  • 10
    Eeeck! Async: false will LOCK UP THE BROWSER for the duration of the ajax call. This is often a horrible user experience. The good solution requires refactoring the code to use a callback or a function call from the success/error functions to continue execution of the process and pass on the result of the ajax call. – jfriend00 Jul 28 '11 at 06:21
  • 6
    Yes, you are right. But I've answered exactly to the question. Artur asked how to make the function to return result. Usability issue is beyond the question. – Pavel Surmenok Jul 28 '11 at 08:30
  • 9
    I guess everyone has their own answering style on SO. If someone may be going in the wrong direction with their question, I'd like to help them understand that rather than only answer the literal question. – jfriend00 Jul 28 '11 at 14:56
4

You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.

Solution 1

function ajaxRefresh(actionUrl, successCallback) {
    $.ajax({
       url: actionUrl,
       success: successcallback
    });
}

But there's a workaround: Just add a callback parameter to the function. This function will be executed when the request has finished.

Solution 2

You can return a jquery deferred.

function ajaxRefresh(actionUrl, successCallback) {
    return $.ajax({
       url: actionUrl
    });
}

Now you can use the function like:

function otherFunction()
{
     ajaxRefresh().success(function() {
        //The ajax refresh succeeded!
     }).error(function() {
        //There was an error!
     });
}

For more information about jquery deferreds look at http://www.erichynds.com/jquery/using-deferreds-in-jquery/.

Arxisos
  • 2,719
  • 20
  • 21
3

You can refactor your code a little bit so that your success callback triggers the next operation that depends on the true/false result. For example, if you currently have something like:

function main() {
  // some code

  if (ajaxRefresh(url)) {
    // do something
  }
}

You would change that to something like:

function main() {
  // some code

  ajaxRefresh(url);
}

function doSomething(successFlag) {
  if (successFlag) {
    // do something
  }
}

function ajaxRefresh(actionUrl) {
  $.ajax({
         url: actionUrl,
         success: function() {
           doSomething(true); // or false as appropriate
         }});
}

You could also put the if test into the ajax callback function instead of in the doSomething() function. Up to you.

Or you can make a synchronous request, and figure out the ajaxRefresh() function's return value after the request is done. I would not recommend that for most purposes.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
2

I am a relatively newbie at this, but here is a suggested work around I came up with which eliminates the need to set asynch to false or anything like that. Just set a hidden field value with the result of the ajax call, and instead of checking return value, check the value of the hidden field for true/false (or whatever you want to put in it).

Example: function doSomething() {

    $.ajax({
        ...blah blah 
        },
        success: function(results) {
            if(results === 'true') {
                $('#hidField').val('true');
            }
            else {
                $('#hidField').val('false');
            }
        }
    });

Then somewhere else where it's required, this doSomething function is called, and instead of checking the result of the ajax call, look for the hidden field value:

doSomething();

var theResult = $('#hidField').val();

if (theResult == 'true') {

...do whatever...

}
Shantha Kumara
  • 3,272
  • 4
  • 40
  • 52
ttemple
  • 1,825
  • 2
  • 17
  • 12
0
function ajaxRefresh(actionUrl) {   
    bool isSucesss=false;
    $.ajax({       
        url: actionUrl,        
        success: function() {   
            isSucesss=true;     
        },
        error:function() {   
            isSucesss= false;     
        }
    });     
    return isSucesss;
}
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
Ashley John
  • 2,379
  • 2
  • 21
  • 36
  • 2
    This should work _if_ you also set the ajax call to be synchronous. Otherwise it will always return false the same as the original code. – nnnnnn Jul 28 '11 at 05:54
0

Use call back functions

Callback Function Queues:-

The beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.

so, here

function ajaxRefresh(actionUrl) {
        $.ajax({
        url: actionUrl,
        success: function() {
             return true;
        }
        error:function(){
             return false;
        }
     });        
    }

You can get more details here

http://api.jquery.com/jQuery.ajax/

Naga Harish M
  • 2,779
  • 2
  • 31
  • 45
  • 3
    Returning true or false (or anything else) from the success and error callback functions isn't going to help because those return values aren't returned to the bit of code that made the `$.ajax()` call. The success and/or error callback functions need to actually directly call the code that should execute on a true or false value. – nnnnnn Jul 28 '11 at 05:57