mark
mark

Reputation: 23

jQuery ajax success event Strangely not working on ajaxSetup

Background:

In this Javascript code, the success event is never fired:

$.ajaxSetup({cache:false,
        success:function(d) {
            console.log("ok from setup with data "+d.toSource())
        },
        complete:function(xhr,ts){
            console.log("Ajax finished reponse:"+xhr.responseText)
        },
        error:function(jqXHR, textStatus, errorThrown){
            console.log("Error")
        }
});
$.getJSON("test2.php",{},function(data){
    //some code here
});

When I do it this way, it works:

$.ajaxSetup({cache:false,                
        complete:function(xhr,ts){
            console.log("Ajax completado con:"+xhr.responseText)
        },
        error:function(jqXHR, textStatus, errorThrown){
            console.log("Error")
        }
});
$.getJSON("test2.php",{},
     function(data){
            //some code here
     }).success(function(d){
            console.log("success applied directly, data "+d.toSource())
        }
);

In both cases the complete event is always fired and the error one never. However, in the second code the success is fired. Obviously for .get() method it's the same.

PHP code:

<?php header("Content-Type:application/json;charset=utf-8");
    //or whatever text/x-json text/plain, even text/html, jquery do the dirty job
echo json_encode(array("stat"=>"1")) ?>

My objectives:

  1. I want to fire the same success event to all ajax requests
  2. I want to use the json data returned by the request in my success event, and if it is possible, without convert the raw jqXHR responseText to a json again

The problem is strange, any ideas?


I read all these questions:

And I'm pretty sure none of them are my problem.

Upvotes: 2

Views: 4251

Answers (1)

Dan A.
Dan A.

Reputation: 2924

Take a look at the ajaxSetup documentation: http://api.jquery.com/jQuery.ajaxSetup/

Note: Global callback functions should be set with their respective global Ajax event handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than within the options object for $.ajaxSetup().

I think that's your problem right there.

UPDATE

If you want your ajax handlers to be global for any ajax request on the page, do something like this:

$(document).ajaxSuccess(function(d){
    console.log("ok from setup with data "+d.toSource());
});

Upvotes: 5

Related Questions