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

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


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.

   $.ajax({      type: "POST",      contentType: "application/json",      url: '/Hello',      data: { name: 'norm' },      dataType: "json"   });

An example of mine that works:

        $.ajax({            type: "POST",            url: siteRoot + "api/SpaceGame/AddPlayer",            async: false,            data: JSON.stringify({ Name: playersShip.name, Credits: playersShip.credits }),            contentType: "application/json",            complete: function (data) {            console.log(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.

$.ajax({   type: "POST",   url: "http://myDomain.com/path/AddPlayer",   data: JSON.stringify({      Name: "Test",       Credits: 0   }),   //contentType: "application/json",   dataType: 'json',   complete: function(data) {       $("content").html(data);  }});​

References:


I can show you how I used it

  function GetDenierValue() {        var denierid = $("#productDenierid").val() == '' ? 0 : $("#productDenierid").val();        var param = { 'productDenierid': denierid };        $.ajax({            url: "/Admin/ProductComposition/GetDenierValue",            dataType: "json",            contentType: "application/json;charset=utf-8",            type: "POST",            data: JSON.stringify(param),            success: function (msg) {                if (msg != null) {                    return msg.URL;                }            }        });    }


So all you need to do for this to work is add:

headers: {    'Accept': 'application/json',    'Content-Type': 'application/json'}

as a field to your post request and it'll work.