62

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Leff
  • 1,968
  • 24
  • 97
  • 201
  • 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? – Felix Kling Nov 08 '16 at 17:35
  • Since you're using jQuery, you can try `$.param({ array: myArray }, true);` – haim770 Nov 08 '16 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 Nov 08 '16 at 17:37
  • @FelixKling I am using laravel on server side – Leff Nov 08 '16 at 17:39
  • 1
    https://stackoverflow.com/questions/18417265/how-to-send-an-array-via-the-url-in-javascript-jquery Check the above link. – Okkyajy Jun 14 '19 at 11:48

8 Answers8

82

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().

rodrigocfd
  • 6,450
  • 6
  • 34
  • 68
  • "encodeURIComponent" is a standard js function? – R.Akhlaghi Feb 15 '21 at 11:12
  • 1
    @rezaakhlaghi: yes, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent – SaeX Mar 06 '21 at 14:56
  • In PHP I've used `urldecode()` as well to convert it all back. So it's `json_decode(urldecode($your_query_string))` – rCgLT Jul 25 '23 at 13:58
22

try this

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

on server: capture and split data.

JohnTrack
  • 389
  • 1
  • 5
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;
Little Santi
  • 8,563
  • 2
  • 18
  • 46
14

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.

bmatovu
  • 3,756
  • 1
  • 35
  • 37
3

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;
StefanBob
  • 4,857
  • 2
  • 32
  • 38
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;
James
  • 1,979
  • 5
  • 24
  • 52
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);

Ahmet Firat Keler
  • 2,603
  • 2
  • 11
  • 22
0
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("_")