3

When passing an object as the data to the ajax call, I am getting some unexpected results. For some reason, jQuery is adding square brackets to my parameter names if their value is an array. For instance...

var obj =
    {
        name: "John Doe",
        courses: [ 1, 2, 4 ]
    };

...becomes name=John+Doe&courses[]=1&courses[]=2&courses[]=4 instead of name=John+Doe&courses=1&courses=2&courses=4.

Why is jQuery adding the square brackets?

Here is a working example: http://jsfiddle.net/BrHSy/

Update:

I expect the above example to produce a string similar to the query string in this example:

<html>
    <head></head>
    <body>
        <form method="GET">
            <input type="hidden" name="name" value="John Doe"/>
            <input type="hidden" name="courses" value="1"/>
            <input type="hidden" name="courses" value="2"/>
            <input type="hidden" name="courses" value="4"/>

            <button>Go!</button>
        </form>
    </body>
</html>

Notice that the query string which is produced by the form (www-form-urlencoded) does not have the square brackets.

1 Answer 1

4

I found my own answer. It looks like jQuery, when encoding the data using $.param, does not specifically www-form-urlencode the data. It is serializing it instead. Prior to jQuery 1.4, the results would have been as expected.

The solution for me, then, is to use the traditional logic instead by passing true:

$.param(obj, true);

This results in: name=John+Doe&courses=1&courses=2&courses=4

When calling $.ajax(), you can set the traditional option to true to have jQuery encode the data in the traditionally expected manner. It seems that traditional should have been the default since jQuery's ajax function, by default, uses the www-form-urlencode content type. But the end result, when the data is sent to the server, is a malformed www-form-urlencode'd chunk of data (according to how HTML forms are handled in general if they have multiple inputs with the same name).

Updated example here: http://jsfiddle.net/BrHSy/1/

Sign up to request clarification or add additional context in comments.

2 Comments

Great, this has been driving me nuts. Setting traditional:true to ajax works. But I don't understand your first line $.param(obj, true);. What is obj?
Hi @PureW, obj is the thing I want to encode, as in the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.