Gábor Varga
Gábor Varga

Reputation: 840

.ajaxPrefilter() jQuery

I would like to filter all ajax response. I found this jQuery function: jQuery.ajaxPrefilter(). Can someone tell me how this works? When the users didn't logged on then I must catch that php response ( fe.: "not_logged_on" ) because the time when it must do as in normal case.

for example:

jQuery.ajaxPrefilter(function( response ){
   if ( response == 'not_logged_on' )
       window.location = "?login";
})

I hope understandable my question.

Upvotes: 1

Views: 2145

Answers (2)

user65839
user65839

Reputation:

The ajaxPrefilter command allows you to modify Ajax requests before they are sent. It doesn't have access to the response, because the request hasn't happened yet.

I believe you are looking for the ajaxSuccess or ajaxComplete events, which trigger whenever an Ajax call completes successfully or completes at all, respectively. They have the xhr parameter that includes the result of the request, which your event handler can examine and use.

Upvotes: 0

Tobias Krogh
Tobias Krogh

Reputation: 21

I would recommend to use jQuery.ajaxSetup. What you want to achieve is that on every ajax call the response is checked. ajaxPrefilter helps you setting up some things before the ajax call is made.

You could solve your problem by using:

jQuery.ajaxSetup({
  success: function(data) {
    // NOTE: data must not necessarily be a string,
    // depends on the requested / returned type
    if (data === "not_logged_on") {
      window.location = "?login";
    }
  }
});

This should fit your needs.

Upvotes: 2

Related Questions