I am calling an ajax function(checkConnection) and because i want a return value i've set the async option to false . Then i also call the notificationConfirm with async : false in order to wait for the function to complete and then update the notifications with getNotifications. Because this process takes some time and i need to inform the user to "wait" I'm fading in the spinner and after i fade it out. But it doesn't work. Can please someone explain me why because I'm new at jQuery or propose me a way to visualize the ajax-call? I have to mention that without those two function calls the fadeIn-fadeOut effect works. thank you in advance
$(document).on('click','.wrapper',function(e){
if ($(e.target).is('#check-notification')){
return;
}
else if ($(e.target).is('.send-email')){
$(this).find('#spinner').fadeIn('fast');
var con = checkConnection("<?php echo site_url('ajax/checkConnection')?>");
if (con == "yes"){
var url = '<?php echo site_url("ajax/sendMail"); ?>';
notificationConfirm($(e.target),url);
$(this).find('#spinner').fadeOut('fast');
$(document).trigger('getNotifications');
}
else {
alert('No connection');
}
}
else{
if ($('.notifications').is(":visible"))
$('.notifications').hide('slow');
}
});
the first function:
checkConnection = function(url) {
var res = $.ajax(url,{
datatype: 'html',
async: false
});
return res.responseText;
};
the second function:
notificationConfirm = function(element, url) {
var data = {
"subject": element.parent('.notification-item').find('.notification-subject').text(),
"profID": element.parent('.notification-item').find('.hidden-prof').text(),
"date": element.parent('.notification-item').find('.notification-date').text(),
"code": element.parents('div').attr('id')
};
$.ajax({
type: 'GET',
datatype: 'html',
url: url,
data: data,
async : false,
error: function() {
alert('// error message //');
},
success: function(res) {
alert(res);
}
});
};
The best approach to show and hide ajax loader is using beforeSend and success callbacks. you can use async:true
. also if you need to execute a code once an ajax request is finished, use the block inside success callback. that is the main reason for that callback. so you don't have to use async:false
for your ajax calls.
example:
$(document).on('click','.wrapper',function(e){
if ($(e.target).is('#check-notification')){
return;
}
else if ($(e.target).is('.send-email')){
$(this).find('#spinner').fadeIn('fast');
checkConnection("<?php echo site_url('ajax/checkConnection')?>");
}
else{
if ($('.notifications').is(":visible"))
$('.notifications').hide('slow');
}
});
checkConnection = function(url) {
var res = $.ajax(url,{
datatype: 'html',
beforeSend: function() {
$("#loading-image").show();
},
success: function(msg) {
$("#loading-image").hide();
if (msg == "yes"){
var url = '<?php echo site_url("ajax/sendMail"); ?>';
notificationConfirm($(e.target),url);
$(this).find('#spinner').fadeOut('fast');
$(document).trigger('getNotifications');
}
else {
alert('No connection');
}
}
});
};