Cannot set content-type to 'application/json' in jQuery.ajax

The Solution to Cannot set content-type to 'application/json' in jQuery.ajax is

It would seem that removing http:// from the url option ensures the the correct HTTP POST header is sent.

I dont think you need to fully qualify the name of the host, just use a relative URL as below.

      type: "POST",
      contentType: "application/json",
      url: '/Hello',
      data: { name: 'norm' },
      dataType: "json"

An example of mine that works:

            type: "POST",
            url: siteRoot + "api/SpaceGame/AddPlayer",
            async: false,
            data: JSON.stringify({ Name:, Credits: playersShip.credits }),
            contentType: "application/json",
            complete: function (data) {
            wait = false;

Possibly related: jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Edit: After some more research I found out the OPTIONS header is used to find out if the request from the originating domain is allowed. Using fiddler, I added the following to the response headers from my server.

 Access-Control-Allow-Origin: *
 Access-Control-Allow-Headers: Content-Type
 Access-Control-Allow-Methods: POST, GET, OPTIONS

Once the browser received this response it then sent off the correct POST request with json data. It would seem that the default form-urlencoded content type is considered safe and so does not undergo the extra cross domain checks.

It looks like you will need to add the previously mentioned headers to your servers response to the OPTIONS request. You should of course configure them to allow requests from specific domains rather then all.

I used the following jQuery to test this.

   type: "POST",
   url: "",
   data: JSON.stringify({
      Name: "Test",
       Credits: 0
   //contentType: "application/json",
   dataType: 'json',
   complete: function(data) {


~ Answered on 2012-03-18 12:36:54

Most Viewed Questions: