Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - set Ajax handler priority

actually the question is as simple as the topic says. Is there any way to give different ajax handlers a higher/lower priority (which means here, that they will fire earlier) ?

What do I mean? Well, I have to deal with a fairly huge web-app. Tons of Ajax requests are fired in different modules. Now, my goal is to implement a simple session-timeout mechanism. Each request sends the current session-id as parameter, if the session-id is not valid anymore, my backend script returns the request with a custom response-header set (value is a uri).

So I'm basically going like this

window.jQuery && jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
    var redirectto = xhr.getResponseHeader( 'new_ajax_location' );
    if( redirectto ) {
        location.href = redirectto;
    }
});

This does work like a charm of course, but my problem is that this global ajax event actually needs to get fired first 100% of the time, which is not the case. Some of those original ajax-requests handlers will throw an error because of missing or unexpected data, in that case, the global handler never gets executed.

Now, I'd be kinda happy if I wouldn't need to go through every single request handler and make it failsafe for invalid session data responses. I'd much more prefer to do the job at one particular place. But how can I make sure my global handler will get executed first ?

like image 976
jAndy Avatar asked Jan 16 '12 13:01

jAndy


1 Answers

If I understand you correctly, you want to add your own callback to json requests everywhere. You could use the ajaxPrefilter hook.

    $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
        options.complete = function (jqXHR2, settings) {
            var redirectto = jqXHR2.getResponseHeader( 'new_ajax_location' );
            if( redirectto ) {
                location.href = redirectto;
            }
        }
    });

You can also change the options there to add the session-id to the request params.

like image 118
Yacine Filali Avatar answered Sep 23 '22 14:09

Yacine Filali