5

Is it possible to set the http content-type request header to 'application/json' when sending a cross domain jquery ajax http request from Internet Explorer?

We're trying to hit a REST WCF service that interprets the content type from the request header when formatting the response. Right now, no matter what we put in the request header it is always returning the data in XML format.

We've tried using the jquery.iecors.js plugin which extends the jquery ajax call to use the XDomainRequest object but that is still ignoring the content-type that is set in our jquery ajax call.

Here's what our ajax call looks like:

makeGETRequest: function (requestUrl) {
    return $.ajax({
        type: "GET",
        url: requestUrl,
        contentType: 'application/json',
        dataType:'json',
        cache: false
    });
}
KodeKreachor
  • 8,852
  • 10
  • 47
  • 64

2 Answers2

11

Just pass the content-type as one of your parameters to the .ajax method:

var retval = jQuery.ajax({
    type:'post',
    url: url,
    contentType: 'application/json',
    data: JSON.stringify(data)
});
slashingweapon
  • 11,007
  • 4
  • 31
  • 50
  • Thank you for your answer, unfortunately we're still getting xml back from our service call. – KodeKreachor Mar 28 '12 at 01:31
  • Can you post the response you're getting back? Especially the response header and part of the body. – slashingweapon Mar 28 '12 at 03:42
  • You should also check that the service you are talking to is configured to response with JSON. See [Suhas](http://stackoverflow.com/a/7479418/1292052) – slashingweapon Mar 28 '12 at 05:57
  • Our problem was that the 'Accept' header needed to be set to 'application/json'. You were first to answer the question I asked so thank you for that, turns out I didn't ask the right question for what we were facing :) – KodeKreachor Mar 30 '12 at 04:22
3

Yes, you could use the contentType parameter:

$.ajax({
    url: '/someurl',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ foo: 'bar' }),
    success: function(result) {

    }
});

Request sent:

POST /someurl HTTP/1.1
Host: example.com
Content-Length: 13
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

{"foo":"bar"}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928