Jon Harding Jon Harding - 5 months ago 25
jQuery Question

jquery wait on response

It's been awhile since I worked with query and I can't for the life of me figure out why this isn't waiting on the response. I looked for answers similar to this post. I must be missing something pretty simple.

The calling function:

$('#cappuccino-button').click(function () {
$('#screen-one').hide();
var hasMilk = IsThereMilk();
if (hasMilk) {
$('#cappuccino-success').show();
} else {
$('#milk-fail').show();
}
}


The function itself:

function IsThereMilk() {
$.ajax({
url: 'http://milkstore/gotany',
type: 'GET',
async: false,
success: function(data){
console.log('*****AJAX' + data.hasMilk);
return data.hasMilk;
}
});
}


Can anyone help me identify why my calling function isn't waiting on the ajax request?

Answer

IsThereMilk() call does not actually return a value. Though if $.ajax() was returned the value would be a jQuery promise object, not a Boolean.

Try adjusting js, to return $.ajax() from IsThereMilk() call, .then() to check if response data.hasMilk

function IsThereMilk() {
    return $.ajax("http://milkstore/gotany");
}

$("#cappuccino-button").click(function () {
    $("#screen-one").hide();    
    var hasMilk = IsThereMilk();
    hasMilk.then(function(data) {
      if (data.hasMilk) {
        $("#cappuccino-success").show();
       } else {
        $("#milk-fail").show();
       }
    })
})

jsfiddle https://jsfiddle.net/r8hc6nna/