Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for AJAX to complete before returning from function?

I have the following

function doAjax()
{
  var result = false;
  $.ajax(url, data)
    .done(function(){
       // Do a bunch
       // of computation
       // blah blah blah
       result = true;
    }).fail(function(){
       result = false;
    });
  return result;
}

function doSomething()
{
  if ( doAjax() == true )
    console.log('success');
  else
    console.log('failed');
}

function doSomethingElse()
{
  if ( doAjax() == true )
    console.log('success');
  else
    console.log('failed');
}

I have a function that runs some ajax, then returns true or false, depending on whether the ajax was successful or not. This ajax function I call from multiple places in my code.

Because the function ends before the ajax finishes, it always returns false. How do I avoid this?

I have read something suggesting that I do a return $.ajax() in my function and then move the .done() and .fail() functions to my doSomething() and doSomethingElse() functions. However, in my .done() method, I do a BUNCH of computation. Lots of code. So the problem is, that if I move the .done() function to my other functions, I am duplicating a bunch of code.

How do I avoid this? Just wrap the computation into it's own function and call it wherever necessary?

like image 646
Jake Wilson Avatar asked Aug 27 '14 06:08

Jake Wilson


3 Answers

Restructure your code to use callbacks instead of returns, like this...

function doAjax(callback)
{
  $.ajax(url, data)
    .done(function(){
       // Do a bunch
       // of computation
       // blah blah blah
       callback(true);
    }).fail(function(){
       callback(false);
    });
}

function doSomething()
{
  doAjax(function(result){
    if (result == true )
       console.log('success');
    else
       console.log('failed');
  });
}

function doSomethingElse()
{
  doAjax(function(result){
    if (result == true )
       console.log('success');
    else
       console.log('failed');
  });
}
like image 71
Soren Avatar answered Sep 22 '22 18:09

Soren


Techincally you can make you ajax synchronous like this:

 $.ajax({url:myUrl, data:myData, async: false})

But this isn't recomended(only for really really specific things).
Otherwise, simply use callbacks as you can see in this example:

var menuId = $( "ul.nav" ).first().attr( "id" );    
var request = $.ajax({   
  url: "script.php",    
  type: "POST",    
  data: { id : menuId },   
  dataType: "html"    
});

request.done(function( msg ) {    
  $( "#log" ).html( msg );   
});

request.fail(function( jqXHR, textStatus ) {    
  alert( "Request failed: " + textStatus );    
});

Read more here.

like image 36
Amir Popovich Avatar answered Sep 19 '22 18:09

Amir Popovich


NEVER do return together with Ajax, it will never work. Use Ajax success function:

$.ajax({
   url: 'http://localhost',
   success: function(data){
        var doStuff = true;
        var responseFromServer = data;
        callSomeFooFunction();
        //return will not work!
   }
})
like image 40
Justinas Avatar answered Sep 20 '22 18:09

Justinas