11

I am using jquery to post Json data to server. However when I make a post request as below,

    $.ajax({
                type        :   'POST'  ,
                url         :   uri,
                data        :   jsonStrJson,
                contentType :   'application/json',
                success     :   successFunction
        });

The http request header content type is not "application/json" even though I posting a json object.

Since it is not applcation/json, the server does not process the requset and returns 415.

Is there a way to set the header using javascript or jquery API?

3
  • 7
    contentTYpe -> contentType ? Commented Jan 17, 2014 at 18:20
  • 2
    very keen eye @JasonP, i missed it Commented Jan 17, 2014 at 18:21
  • Appreciate it. Thank you very much i posted this thiniking i dint understand the Jquery API for AJAX. My bad. Thank you Jason Commented Jan 17, 2014 at 18:23

3 Answers 3

25

Can you try this,

$.ajax({
    beforeSend: function(xhrObj){
        xhrObj.setRequestHeader("Content-Type","application/json");
        xhrObj.setRequestHeader("Accept","application/json");
    },
    type: "POST",
    url: uri,       
    data: jsonStrJson,               
    dataType: "json",
    success: function(json){
       console.log(json);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

5

"contentType" instead "contentTYpe" should also solve the problem. ;)

Comments

0

Also for setting http request header parameters you can try this approach:

$.ajax({
       type        :   'POST'  ,
       url         :   uri,
       data        :   jsonStrJson,
       headers     : { 'Content-Type': 'application/json' }, //this line
       success     :   successFunction
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.