Darren
Darren

Reputation: 2938

Why are my form field names arriving with square brackets when I post via jquery?

I am using jquery's POST api (https://api.jquery.com/jquery.post/) to send some form data to my server. When the server parses the request one of the fields has square brackets added to the name, eg. foo becomes foo[]. This is breaking the form handling on the server. What's going on?

Upvotes: 2

Views: 600

Answers (1)

Darren
Darren

Reputation: 2938

When you send an array or a form where multiple inputs have the same name, jquery adds the square brackets.

It is totally valid to send duplicate params in url encoded data by simple repetition eg. foo=bar&foo=baz&foo=quxis a valid thing to send to a server. Most servers will parse this into a variable called foo that contains an array of the values.

In order to make jquery behave 'correctly' (ie. send the fields with their actual names), it is necessary to add a {traditional: true} option to the request.

eg:

let data = {foo: ['bar', 'baz', 'quz']};
$.post({url:'/myurl', data: data, traditional: true, success: onSuccess});

I will admit to being baffled by jquery's decision to silently rename fields - this is potentially going to waste a lot of time (as it did for me) trying to debug mysterious errors.

Upvotes: 3

Related Questions