67

I would like to pass an array and added to a link on my page as a URL parameter, because later on the server side I need the values from the array. How should I do that?

myArray = ['aaa', 'bbb', 'ccc'];

$('#myLink').attr({"href" : '/myLink?array=' + myArray});

I am not sure if that is the proper way of doing this?

5
  • 2
    "How should I do that?" That really depends on what server side language you are using and how it expects the data to be formatted. E.g. does the server expect JSON? Or a parameter per value? A comma separated list of values? Something else? Commented Nov 8, 2016 at 17:35
  • Since you're using jQuery, you can try $.param({ array: myArray }, true);
    – haim770
    Commented Nov 8, 2016 at 17:36
  • The answer is you can't, not with Javascript. All solutions you end up would not be actually something you would pass. What you can do is pass an array like parameter and throw back with you server side languague. Why you need to pass the entire array anyway?
    – Marco
    Commented Nov 8, 2016 at 17:37
  • @FelixKling I am using laravel on server side
    – Leff
    Commented Nov 8, 2016 at 17:39
  • 1
    stackoverflow.com/questions/18417265/… Check the above link.
    – Okkyajy
    Commented Jun 14, 2019 at 11:48

9 Answers 9

86

You can serialize the JSON:

myArray = ['aaa', 'bbb', 'ccc'];
var arrStr = encodeURIComponent(JSON.stringify(myArray));
$('#myLink').attr({ href: '/myLink?array=' + arrStr });

If your parsing (on the next page) is done via JavaScript too, you'll conversely use JSON.parse(). In PHP it would be json_decode().

3
22

try this

$('#myLink').attr({"href" : '/myLink?array=' + myArray.join(',')});

on server: capture and split data.

0
17

It should not depend on the server side: By the URI standard specification, all parameters must have one name and should have one value. But there can be several parameters with the same name, which is the right way to serialize an array:

http://server/context?array=aaa&array=bbb&array=ccc&otherparameter=x

You could do it like this:

var s="";
for (var i=0;i< myArray.length;i++)
{
  s+="&myArray="+myArray[i];
}
var url="http://server/context?"+s;
6
  • 3
    this good but need to edit s+="&myArray="+myArray[i]; to s+="&myArray[]="+myArray[i];
    – megyptm
    Commented Apr 22, 2020 at 8:02
  • 1
    @megyptm No, not at all. My approach will produce multiple values to parameter named "myArray". As you say, it would be to a parameter named "myArray[]". Commented Apr 22, 2020 at 10:33
  • 1
    Why not use URLSearchParams? with methods .append and .toString Commented Nov 15, 2021 at 18:44
  • 1
    @LittleSanti Contrary to your first sentence, the required format deos depend on the technology on the server side. The specification of a URI makes no judgement on this; the CGI specification does, but it's not universally followed. The original user who asked the question clarified they were using Laravel, a PHP framework; and in PHP, ?myarray=1&myarray=2 will keep only the last value, but ?myarray[]=1&myarray[]=2 will format them into an array.
    – IMSoP
    Commented Apr 11 at 16:06
  • @IMSoP Interesting, thanks. There is always some framework which unnecessarily complicates things that should be kept simple. :-) Commented Apr 11 at 19:03
15

I'd go with this approach,

var myArray = ['aaa', 'bbb', 'ccc', ];

var myArrayQry = myArray.map(function(el, idx) {
    return 'myArray[' + idx + ']=' + el;
}).join('&');

// myArray[0]=aaa&myArray[1]=bbb&myArray[2]=ccc

Then, I retrieve the URL query params as an array on the server side.

4

How to pass an array of strings as URL parameters:

const myLink = 'https:/example.com/api'
const myArray = ['aaa', 'bbb', 'ccc'];
let apiUrl = `${myLink}/query?`;

myArray.forEach((x, i) => {
  if (i === 0) {
    apiUrl += `array=${x}`;
  } else {
    apiUrl += `&array=${x}`;
  }
});

console.log(apiUrl);
document.body.innerHTML = apiUrl;

2
myArray = ['aaa', 'bbb', 'ccc'];
myArrString = JSON.stringify(myArray.join("_"))

$('#myLink').attr({"href" : `/myLink?array=${myArrString}`});

And then when you need it later on you can parse it and then get back your array like so

JSON.parse(myArrString).split("_")
1

My approach:

var myArray = ['aaa', 'bbb', 'ccc'];
var baseUrl = '/myLink';
var paramName = 'array=';

var arrayAsString = '?' + paramName + myArray.join('&' + paramName);
var urlWithParams = baseUrl + arrayAsString;

window.location.href = urlWithParams;
0

One another way to do that is as the following

import Router from 'next/router'

Router.push({
  pathname: '/search',
  query: {searchTerm: searchRef.current ? searchRef.current["value"] : '', codeSets: JSON.stringify(selectedCodeSets)}
}, '/search');

selectedCodeSets in this example is an array from state data

const [selectedCodeSets, setSelectedCodeSets] = useState<any>(['1']);

We can parse that data in the directed page like below

import {withRouter} from 'next/router'

const DaComponent = (props) => {
  useEffect(() => {
        let codeSets = JSON.parse(props.router.query.codeSets);
  }, [props.router]);
};

export default withRouter(DaComponent);

0

I would simply do it like this.

const BASE_URL = "www.yourUrl.com/yourEndpoint";
const getArrayQuery= (paramName, someArray) => {
   return someArray
       .map((x) => `${paramName}=${x}`)
       .join('&');

const query = getArrayQuery("array", someCoolArray);
const url = `${BASE_URL}?${query}`;

Quite possibly you wouldn't want to declare variables for both BASE_URL and later the whole url. But this would get the job done with very little complexity.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.