Shahzeb Khan
Shahzeb Khan

Reputation: 3642

sending json data to server returns 400 bad request

I want to send my string value to server as json data, but i get 400 bad request. here is the code how i am sending data.

dataString = '{"comment":"'  +dataString+ '"}';
        dataString = '[' + dataString + ']';

         $.parseJSON(dataString);
         console.debug("After parsing : "+dataString);

        $(form_element).clearForm();
        $.ajax({
            type : "POST",
            url : loc,
            cache : false,
            data : dataString,
            dataType: 'json',
            contentType: "application/json",

            success : function(data) {
                console.debug("After success");
            }

When i debug the code, the @RequestParameter "comment" have null value. Kindly help me, thanks in advance.

Upvotes: 0

Views: 2146

Answers (2)

secondflying
secondflying

Reputation: 871

I think you shoud pass json object NOT json array.

var dataString = '{"comment":"test"}';
    //dataString = '[' + dataString + ']';  //delete this, NOT array
var obj = $.parseJSON(dataString);
console.log(obj);

$.ajax({
    type : "POST",
    url : url,
    cache : false,
    data : obj,
    contentType:"application/json; charset=utf-8",
    dataType:"json",

    success : function(data) {
        console.debug("After success");
    }
});

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382454

The parseJSON function returns an object.

You should do

var obj = $.parseJSON(dataString);

$.ajax({
        type : "POST",
        url : loc,
        cache : false,
        data : obj,

That's supposing you really need to build your string as you do. It's generally simpler to just build your object instead of making a json string, parsing it then asking jQuery to serialize it again.

Upvotes: 2

Related Questions