Michael Sharman
Michael Sharman

Reputation: 91

jQuery ajax not transmitting as utf-8

I'm using an older version of backbone.js (0.5.3) with jQuery 1.7.2, and when Backbone.sync executes (which is a wrapper for jQuery $.ajax()) it sets the contentType explicitly as:

params.contentType = 'application/json';

This looks like what I want, however the content doesn't appear to be sent as utf-8. I'm testing with an ndash, here is my sample string:

Mathematics K–10

After submitting to the server I get:

Mathematics K–10

Now, if I change the contentType (in backbone.js) to:

params.contentType = 'application/json; charset=utf-8';

Everything works as expected and I get the correct ndash character. This is also the behaviour if I comment out the original contentType line in backbone.

The jQuery docs suggest that:

Data will always be transmitted to the server using UTF-8 charset

But it seems that if you explicitly set your contentType, then you also need to set a character set.

My question is, does this behaviour make sense? I would have thought we always want the default to be utf-8 (as the jQuery docs state) even if we explicitly change the contentType. Has anyone else come across this or have any information that might help me out?

Upvotes: 1

Views: 2194

Answers (2)

Georgios Syngouroglou
Georgios Syngouroglou

Reputation: 19944

You could extend the ajax function to provide custom headers for backbone ajax calls, like the above,

Backbone.ajax = (function(_protoAjax) {
    var _Backboneajax = _protoAjax;
    return function(options) {
        var defaultOptions = {
            headers: {
                "Accept": "application/json; charset=UTF-8",
                "Content-Type": "application/json; charset=UTF-8"
            }
        };
        options = $.extend({}, defaultOptions, options)
        return _Backboneajax.call(this, options);
    };
})(Backbone.ajax);  

Or you could set this headers on all JQuery Ajax calls (not only the Backbone ajax calls), like the above,

$.ajaxSetup({
    headers: {
        "Accept": "application/json; charset=UTF-8",
        "Content-Type": "application/json; charset=UTF-8"
    }
});

Upvotes: 1

Lee Goddard
Lee Goddard

Reputation: 11173

The HTTP spec states the the content-type sets the character sense. Perhaps the jQuery docs should be clearer.

Upvotes: 0

Related Questions