Generate Url with Parameters from an Array

Generate URL with parameters from an array

All you need is http_build_query:

$final = $url . "?" . http_build_query($subids);

Passing arrays as url parameter

There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:

$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));

will return

string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"

http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.

How to pass a JavaScript array as parameter to URL and catch it in PHP?

You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:

var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"

Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:

fetch('script.php?traffic=' + trafficFilterHolderJoin)

Then in your php script file you will convert the comma-separeted format to php array format using the explode function:

$traffic = explode(",", $_GET['traffic']);

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}

Replace an array parameter in a url request using URLSearchParams and $.param()

What you'll need to do is remove the foo[] entry, then iterate the values array from .getAll('foo[]') and .append().

For example

const usp = new URLSearchParams([  ['foo[]', 1],  ['foo[]', 2],  ['bar', 3],  ['bar[]', 4],  ['page', 1]])
console.info('original:', decodeURIComponent(usp.toString()))
// get all 'foo[]' entriesconst foos = usp.getAll('foo[]')// incremenent the last valuefoos[foos.length - 1]++
// remove 'foo[]'usp.delete('foo[]')
// iterate values and appendfoos.forEach(foo => usp.append('foo[]', foo))
console.info('updated:', decodeURIComponent(usp.toString()))


Related Topics



Leave a reply



Submit