arb
arb

Reputation: 7863

jQuery.ajaxSetup() Is Being Ignored

In a JS file I have this:

$.ajaxSetup({
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: {},
    error: function (jqXHR, textStatus, errorThrown) {
        debugger;
    }
});

Then further on in the file I instantiate an object that has an AJAX call in it's constructor to fill out some values.

function RequestViewModel() {
    var self = this;
    (...)
    // Initalization Methods
    $.ajax({
        url:ajaxAddress + 'LoadStates',
        success: function (data) {
            debugger;
        }
    });
}
var model = new RequestViewModel();

However, when the ajax call is made in the code, 'xml' is being used as the dataType instead of JSON. This is causing my web service call to break and I always get sent to the error callback of the AJAX call. If I move the settings inside the actual AjAX call, the call works and data is returned from the server. For some reason, the global setting isn't being honored.

My question is why isn't this working? I've used this same technique several other times without this problem.

I'm using jQuery version 1.7.1.

UPDATE

It seems like the problem is on line 7517 of the jQuery file. It is doing an IF statement that is being evaulated to false and is skipping over setting the correct Content Type in the request header.

Upvotes: 2

Views: 6942

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34196

  • Try putting your .ajaxSetup inside a document ready wrapper.(NOT likely the cause though)
  • Try using jQuery.ajaxSetup instead of $.ajaxSetup
  • It is recommended that global event handlers not be in the ajaxSetup. move error: to $.ajaxError( instead:

    jQuery.ajaxError( function (e, jqxhr, settings, exception) { alert(settings.url + " Failed");
    });

Example if you have a div with a log class (puts some text in if any error occurs:

$("div.log").ajaxError(function() {
  $(this).text( "Triggered ajaxError handler." );
});

NOTE: when you refactor, make sure to remove the LAST comma.

Also, if you are using the latest version of jQuery (1.7.1 at the moment) you can simplify:

contentType: "application/json; charset=utf-8",

to

contentType: "application/json",

EDIT: quick, dirty global handler:

$(document).ajaxError(function(e, xhr, settings, exception) {
    alert('error in: ' + settings.url + ' \\n'+'error:\\n' + exception);
}); 

EDIT2: SOME resources also put an empty data set sent as: (with quotes)

data: "{}",

Upvotes: 3

KOGI
KOGI

Reputation: 3989

Where is .ajaxSetup() being called? Are you using any other plugins? It's possible some other library is misbehaving and overwriting your options.

Upvotes: 0

Related Questions