5

I would like to make an ajax call, and in the data object I need to have several values in the same key.

var data = {
    foo: "bar",
    foo: "baz"
}

$.ajax({
    url: http://example.com/APIlocation,
    data: data,
    success: function (results) { console.log(results) },
    dataType: 'json'
});

The intention is to get a URL that looks something like:

http://example.com/APIlocation?foo=bar&foo=baz

I tried structuring the data like this:

var data = {
    foo: ["bar","baz"]
}

Which unsurprisingly, did not work because it encodes the url like this:

http://example.com/APILocation?foo%5B%5D=bar&foo%5B%5D=baz

I tried the solution here, but could not make it work.

1 Answer 1

18

You can use jQuery's $.param to convert an array to a parameter string that contains the same key multiple times. Set the second argument to true so it doesn't get url-encoded, and then just pass that string to the data property in the AJAX call:

var data = $.param({ foo: ['bar', 'baz'] }, true);
// data is now 'foo=bar&foo=baz'

$.ajax({
    url: 'http://example.com/APIlocation',
    data: data, // Will handle the string correctly.
    success: function (results) { console.log(results) },
    dataType: 'json'
});

Or, with an object, you can set the traditional property to true:

var data = {
    foo: ["bar","baz"]
};

$.ajax({
    url: 'http://example.com/APIlocation',
    data: data,
    success: function (results) { console.log(results) },
    dataType: 'json',
    traditional: true
});
Sign up to request clarification or add additional context in comments.

4 Comments

Using jquery.param() gives me a URL like: example.com/APIlocation?foo=foo%3Dbar%26foo%3Dbaz
Setting the traditional property to true on the ajax call worked. Thank you.
For jQuery.param to work, you need to pass true as the second argument. I'm glad this worked for you, no problem.
(the second argument to jQuery.param is also traditional)

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.