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?
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');
});
}
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.
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!
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With