I have been searching for so long, time to ask for help...
What I am trying to do is just to show an alert()
after another function has finished executing. The part I am referring to is the success
of the ajax
call.
jQuery(document).on('click','a.remove_from_cart',function(event){
event.preventDefault();
startWait();
var self = jQuery(this);
jQuery.ajax({
url:ajaxurl,
type:'post',
cache:false,
data:{
action: self.data('action'),
post_id: self.data('id'),
nonce: self.data('nonce')
},
success:function(data){
if (data) {
// some action
}
// please help me here
stopWait().then(alert(data));
}
});
});
startWait()
and stopWait()
are two functions that just add/remove classes from 2 html elements:
function startWait() {
document.getElementById('wait').classList.add('active');
document.body.classList.add('wait');
}
function stopWait() {
var d = jQuery.Deferred();
document.getElementById('wait').classList.remove('active');
document.body.classList.remove('wait');
return d.promise();
}
They just show/hide an overlay with a spinner inside.
In the success
method of the ajax
call I would like to first stopWait()
aka hide the overlay, then alert some info.
I tried callbacks, promises, jQuery deferred and I can't remember what else, I just can not make this work, always, first the alert()
gets shown then only after I close the alert(data)
the stopWait()
does its job. Why?
Please can you help me understand what I am doing wrong here? Thanks!
EDIT 1: wrapping the alert() inside a function does not solve the issue. Now the stopWait() gets executed but then no alert is shown. Please check the codepen: https://codepen.io/usainicola/pen/GxOzqz
EDIT 2: issue solved, here the working codepen: https://codepen.io/usainicola/pen/MVORyd
you have to resolve the promise before returning it like
function stopWait() {
var d = $.Deferred();
document.getElementById("wait").classList.remove("active");
d.resolve();
return d.promise();
}
please take a look of changed codepen edited code pen