Question

I'll note that this code is not something I built, I'm simply making some UI changes using a plugin on a system that's already in place.

I'm building a plugin that's utilizing blockUI (yes, I need to build a plugin with a plugin) in order to display a loading icon over certain elements when an Ajax call is fired, however this one in particular calls an alert() if the success() event doesn't get the response it needs.

The result of this is my loading icon calling fadeOut() after the alert fires, which is not what I want it to do.

When I call the function I'm building, I pass in $.post() complete with the settings and options I need, like this:

$.fn.startLoading({            
    element: $("div"),
    ajax: $.post('some.url',
    {
        //Ajax settings...
    }, function (response) {   //This is the success function, right?
            if (good) {
                //stuff
            }
            else
                alert("Bad!"); //This happens BEFORE fadeOut()
        }
    }, 'text')
    .error(function (msg) {
        alert('Worse error!');
    })
});

My plugin's function takes all of this in as one options parameter, like so:

$.fn.startLoading = function (options) { ...

I then access the $.post() call like this:

if (options.ajax)
    ajax = options.ajax;

This is where I'm stuck. I need to make sure that the fadeOut() happens before the success event is fired. How can I do this using the ajax variable I've created in my plugin?

Was it helpful?

Solution

One easy way is with ajaxComplete, ajaxSuccess etc http://api.jquery.com/category/ajax/

Those are global ajax handlers that grab ALL ajax requests sent via jQuery... so you could set a handler in there and whitelist your own callback elements etc so that you ignore ones that are not of your concern.

In my testing these global handlers fire BEFORE the handlers of the specific ajax call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top