Shahzeb Shahzeb - 6 months ago 7
Javascript Question

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.

Answer

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");
    }
});