benhowdle89
benhowdle89

Reputation: 37494

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'?

Upvotes: 4

Views: 10542

Answers (3)

Webmaster G
Webmaster G

Reputation: 532

What about $.param()?

var my_data = {};
my_data.post_name = 'post_value';
$.ajax({
    url:'/post_url.php'
    data:$.param(my_data);
    ...
});

Upvotes: 0

Kevin B
Kevin B

Reputation: 95066

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.

Upvotes: 3

Heretic Monkey
Heretic Monkey

Reputation: 12113

It is still sending the request in the second attempt; it is simply that your server does not understand the request. That is because jQuery automatically processes the formValues data into a query string before sending the data. See the documentation:

data

Type: Object, String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

So, you must use JSON.stringify(), or not use JSON. Note that setting processData to false won't help, since it will simply send the string [object Object] to your server. See also this question.

Upvotes: 3

Related Questions