[Fixed]-How do I remove the square brackets at the end of a JS variable name during AJAX calls?

35👍

This is default behavior in jQuery 1.4+…if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:

$.ajaxSetup({traditional: true});

Note this affects all requests… which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.

-1👍

When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.

POST requests work in exactly the same way (unless the json is sent as one long json string).

In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.

I’m not sure how Django parses query strings.

👤Eric

-3👍

The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django’s way of telling you it is an array. You could probably implement your own print function which does not show them.

👤Andy

Leave a comment