5

I am trying to send the same parameter name with multiple values, but even after reading the posts on SO can't figure out how to do it... I want to have an array of destination_input:

var myObject = {
                  search_zip: params.search_zip,
                  search_distance: params.search_distance,
                  filter_opts: params.filter_opts,
                  page: params.page,
                  destination_input: ['323 w concord pl #8, chicago, il', '11 e hubbard, chicago, il']
            };

but this creates a query string of:

search_zip=60614&search_distance=1&filter_opts=discount_check%2Cneed_device_check%2Cauto_track_check&destination_input%5B%5D=323+w+concord+pl+%238%2C+chicago%2C+il&destination_input%5B%5D=11+e+hubbard%2C+chicago%2C+il

As you can see it keeps adding %5B%5D to the destination_input such as &destination_input%5B%5D=11+e+hubbard%2C+chicago%2C+il

This means everything gets messed up on the backend. Any ideas?

SharpC
  • 6,974
  • 4
  • 45
  • 40
Kamilski81
  • 14,409
  • 33
  • 108
  • 161

3 Answers3

14

I'm going under the assumption that your backend is not PHP, since PHP expects [] to indicate that an GET parameter is multivalued. That means that your backend will treat multiple GET arguments with the same key as elements of an array, correct?

Going off that assumption, you just need to tell jQuery to not automatically add [] when it is turning an array into a GET argument string.

To so that, you have to pass the 'traditional': true argument as an option to jQuery's ajax function.

Search 'traditional' on here: http://api.jquery.com/jQuery.ajax/

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 2
    I'm just wondering why false is the default here. Do you know why? – autra Apr 22 '14 at 08:41
  • 1
    @autra I can't say for sure, probably because jQuery came into being at a time when PHP was very popular and defaulting to the most common use-case makes sense. – loganfsmyth Apr 22 '14 at 14:59
  • I ran into this problem trying to pass an array of IDs to a PrimaryKeyRelatedField on a DRF serializer. The jQuery ajax request kept tacking on these brackets. Spent hours trying to figure it out. Days later, find this. TY. – Rob May 05 '20 at 04:23
0

%5B and %5D are the URL encoded values of [ and ] respectively. They must be part of your input.

In your PHP execute urldecode(inputString) to decode the values.

Jivings
  • 22,834
  • 6
  • 60
  • 101
0

You're currently using an HTTP GET AJAX request to send your data. An HTTP POST instead looks to be more apt for your needs, actually.

Not only are you throwing in an object into your service, but with an object of that complexity, you may soon find yourself running out of characters if you're embedding your data on your query string.

Community
  • 1
  • 1
Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66
  • I've been using a POST and I'm experiencing exactly the same problem in the encoding of the content. – SharpC Nov 01 '16 at 13:15