views:

25

answers:

1

Hello,

what I'm trying to do is to automatically launch a function before going in the $.ajax({success}); method. I've this:

$("body").ajaxSuccess(
    function(event, XMLHttpRequest, ajaxOptions) {
        alert("ajaxSuccess");
    }
);

and :

$.ajax({
    url: ".",
    success: function() {
        alert("success");
    }
);

My problem is that I first see "success" and then "ajaxSuccess" or would have the opposite. Is it possible? Any other solution?

Problem is the same with $.ajaxError() ...

Thanks

A: 

you can use the following:

dataFilter(data, type)

to intercept the request when it first comes back from the server. This isn't exactly for what you wanted to use it for, but it's a universal pre-success routine.

Pre-Error? maybe a global error handler will work for you?

var obj = {
   someHandler: function(data, xmlObj, status) {},
   someHandler2: function(data, xmlObj, status) {},
   someErrorHandler: function(xmlObj, status, error) {},
   someErrorHandler2: function(xmlObj, status, error) {}
}

jQuery.ajax({
   success:function(data, xmlObj, status) {
      // decide based on data what the run 2nd
      if (data.success) {
         obj.someHandler(data, xmlObj, status);
      }
      else {
         obj.someHandler2(data, xmlObj, status);
      }
   },
   error: function(xmlObj, status, error) {
      // decide based on data what to run 2nd
      //same as above.
   }
});

I do something similar to this in one of my projects. I have a global Error object, where I execute an error handler based on the TYPE of error that comes back from the server. I found this to be an easy and fast way to create good error handling for AJAX

Anatoly G
Hello, problem is, I've no way to distinguish the xhr.status in the dataFilter method and have no way to launch one or another function. In my case I would launch two separate function in each case.
Arnaud F.
If you make the calling of the second function generic, you can, for both cases, use a global success/error function and CALL the specialized function at the end. Maybe some sort of an object that decides which secondary function to call?
Anatoly G
Have you some piece of code, i'm not sure to understand very well... :(
Arnaud F.