smartnut007
smartnut007

Reputation: 6423

Sending JSON content type + JavaScript objects ( jQuery ajax )

I am having trouble sending a JavaScript objects over a http request. The http endpoing only accepts json content-type ("application/json" or "text/json")

I am not sure why data2 ( stringified json ) works fine But, data1 ( json object ) throws http 400 Bad Request. i.e why is jQuery not serializing the json object to a valid json string for the server to process.

var data1 = ({ rating : 3 });  //does not work
var data2 = '{ "rating" : 3}'; //works fine

$.ajax({
    url : "/rate",
    data : data1,
    type : "POST",
    contentType: "application/json",
    success: function(json){
        console.log("Ajax Return :"+json);
    }
});

Upvotes: 1

Views: 8428

Answers (5)

beastieboy
beastieboy

Reputation: 883

I realize this is an old post but here is the solution that worked for me. Setting the dataType as 'json' and removing the contentType altogether should do the trick. Here's the full code:

var data1 = { rating : 3 };

    $.ajax({
        url : "/rate",
        data : data1,
        dataType: 'json',
        type : "POST",
        //contentType: "application/json",
        success: function(json){
            console.log("Ajax Return :"+json);
        }
    });

Upvotes: 0

Ivy
Ivy

Reputation: 887

Setting dataType to 'json' should work. Then you don't have to use JSON.stringify.

$.ajax({
    type: 'POST',
    url: '/rate',
    data: { rating : 3 },
    dataType: 'json',
    success: function (d) { ... }
}

Upvotes: 1

smartnut007
smartnut007

Reputation: 6423

By default data parameter values that is part of any ajax jQuery call, converts the JS object into a url-form-encoding i.e "param1=value&param2=value" string. This is the case for both GET and POST requests.

Interestingly, even if you explicitly specify { contentType : "application/json" } in the ajax method call, only the appropriate header is set, the JS object you pass as value for the data parameter is not converted to a JSON string ( one always hopes for more intelligence ), but still gets encoded as url-form-encoding. So, one has to explicitly convert the JS object to JSON string.

There are a options for doing so,

  1. JSON.stringify(obj); Its part of Javascript, I believe comes comes from ECMA 5 standard. Easiest, but the down side is it does not work in older browsers IE6 and before.
  2. jQuery json plugin that also has some additional features.
  3. Code from json.org

So, now my POST request that needs a json body would work like this.

var dataStr = JSON.stringify({ rating : 3 });  

$.ajax({
    url : "/rate",
    data : dataStr,
    type : "POST",
    contentType: "application/json",
    success: function(json){
        console.log("Ajax Return :"+json);
    }
});

Note: Effect of "processData" boolean parameter Some answer here mentioned that one has to set { processData : false }. But, this is not the case. This has an effect only when the type of "data" parameter is not a string. If its not a string then the default behavior is to convert the Object into url-form-encoding. But, this is mostly useless I think because if you pass a regular Object and processData is set to false, then it tries to do (data).toString which results in "[Object] [Object]" which is pretty useless.

Upvotes: 2

robbymurphy
robbymurphy

Reputation: 741

data1 is an object, data2 is a string. They will be sent to the server as such.

Upvotes: 0

Kevin B
Kevin B

Reputation: 95022

If you want to send a json string, you need to set processData equal to false, otherwise jQuery will process what is passed to data and convert it into a param string.

$.ajax({
    url: "/rate",
    data: data2,
    processData: false,
    contentType: "application/json",
    success: function(json) {
        console.log("Ajax Return :" + json);
    }
});​

Recently answered this here i guess: Setting the POST-body to a JSON object with jQuery

Upvotes: 6

Related Questions