Reputation: 4946
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?
Upvotes: 1
Views: 2035
Reputation: 4926
Jquery when
can be used to achieve similar results.
This is first piece of code that I've written that uses when
$.when( loadMoreComms() ).then(function( data, textStatus, jqXHR ) {
{#var comsect = $('#comment-box-section');#}
$('.loader').css('display', 'none');
});
and this is my loadmoreComms()
function loadMoreComms() {
return $.ajax({*put you ajax code here*});
}
Read more about jquery when
here
Upvotes: 0
Reputation: 1
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/
Upvotes: 2
Reputation: 2302
Have you try to move the condition hasMilk in ajax success?
function IsThereMilk() {
$.ajax({
url: 'http://milkstore/gotany',
type: 'GET',
async: false,
success: function(data){
console.log('*****AJAX' + data.hasMilk);
if (data.hasMilk) {
$('#cappuccino-success').show();
} else {
$('#milk-fail').show();
}
}
});
}
$('#cappuccino-button').click(function () {
$('#screen-one').hide();
IsThereMilk();
}
Upvotes: 0