1

I’m trying to pass an array to a php script as part of an Ajax call. Whilst POST might be simple, it seems GET is the right technique to do this, I’m also making the api code so it can be either way that I send to it. Therefore I want to put the array contents into the url as 2 separate parameters of the request.

After a bit of reading about loops I found the suggestion of using “spread”: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

However I’m not clear how to use it properly. This was my code:

const arg = ['p0', 'p1'];
callMe(arg);

function callMe(…arg){
// ajax GET request
   let url = `api.php?p0=${1}&p1=${2}`;
   // rest of code…
   console.log(arg);
}

This still prints out as an array. How should I be using spread to get p0, p1 put into a url from an array?

Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • 1
    Ewww. POST would be the best way, so you don't need to refresh the page; send the XHR over in a multi-form. GET would be nice for searches/paginations to share results however in URL. – BGPHiJACK Dec 31 '21 at 14:31
  • I heard GET was better when asking for api results, but if it doesn’t matter are you saying I should put array in post instead? – Jimmy Dec 31 '21 at 14:34
  • 1
    This is what POST is meant for. You may encounter issues doing this with GET as it will increase the length of the request URI. For some servers, they will not accept requests if the URI exceeds a certain length. https://stackoverflow.com/questions/7724270/max-size-of-url-parameters-in-get#:~:text=Please%20note%20that%20PHP%20setups,has%20a%20default%20of%208000. – GenericUser Dec 31 '21 at 14:48

1 Answers1

1

You're actually using the rest syntax, which is how you let a function have an infinite number of arguments which will be presented as an array of arguments.

function foo(...args) {
   console.log(args);
}

foo('hello', 1, 'bar', true);

But what you're looking for is to use the spread syntax when passing the args to the callMe function.

See the example below. Here we expect two parameters p0 and p1. When using the spread syntax we pass each item in the array as an argument to the callMe function.

const args = ['foo', 'bar'];

function callMe(p0, p1){
   let url = `api.php?p0=${p0}&p1=${p1}`;
   console.log(url);
}

callMe(...args); // Same as callMe(args[0], args[1]);
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32