benhowdle89 benhowdle89 - 3 months ago 9
jQuery Question

dataType: 'json' vs data: JSON.stringify(obj) in $.ajax

I have this data structure:

var formValues = {
TemporaryToken: a.userStatus.get("TemporaryToken"),
        MemorableWordPositionAndValues:[
            {
                Position: a.userStatus.get("MemorableWordPositions")[0],
                Value: this.$('[name="login-memorable-character-1"]').val()
            },
            {
                Position: a.userStatus.get("MemorableWordPositions")[1],
                Value: this.$('[name="login-memorable-character-2"]').val()
            },
            {
                Position: a.userStatus.get("MemorableWordPositions")[2],
                Value: this.$('[name="login-memorable-character-3"]').val()
            }
        ]
}


And when I send it with $.ajax like so:

$.ajax({
url:url,
type:'PUT',
//dataType:"json",
data: JSON.stringify(formValues),
success:function (data) {

}
});


It sends the request. However, if I send it like so:

$.ajax({
url:url,
type:'PUT',
dataType:"json",
data: formValues,
success:function (data) {

}
});


I receive a 400 Bad Request. Is this a problem on the server or is JSON.stringify doing something different to just setting the dataType to 'json'?

Answer

The server is expecting a JSON string, not form parameters. JSON.stringify converts your form parameters object/array into a JSON string, which is what your server appears to be expecting.