Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting JSON using JQuery and to set HTTP content type - 'application /json'

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?

like image 871
linux developer Avatar asked Jan 17 '14 18:01

linux developer


1 Answers

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);
    }
});
like image 87
Krish R Avatar answered Oct 02 '22 13:10

Krish R