I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked
so that people can share their teams
You can make use of serialize() and urlencode PHP built-in function to pass an array as URL param. The serialize() function will return a sequence of bits for the input given and the urlencode will again encode the values as well the special characters available in it.
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
A URL which contains a page on your site should NEVER have a "/" after it (e.g. "foo. html/") A URL should always have a single question mark in it "?" URL Query String parameters should be separated by the ampersand "&"
You can use an array directly in a url, however you would need to serialize the array into a string. like this player[]=one&player[]=two
here is a little function to automate it.
when using url's you should always use encodeURIComponent
to encode any non url friendly characters. The players are an array so we map over it and get a new array that has been encoded.
After that we simply need to join the array with &
const players = [
'player Name 1',
'playerName2',
'playerName3'
]
const parameterizeArray = (key, arr) => {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
console.log(parameterizeArray('player', players))
The only difference is the function declaration style, everything else is standard ES5
function parameterizeArray(key, arr) {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With