Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arrays as parameters with jQuery AJAX?

Tags:

jquery

ajax

I have an AJAX call in the following format:

$.get('/controller/method/',
  {
    parameter1: value1,
    parameter2: value2
  },
  function(data) {
    if (data) {
    }
  else {
  }
});

Is it possible to pass an array as a parameter?

parameter3: new Array(1, 2, 3)
parameter4: new Array('one' => 1, 'two' => 2, 'three' => 3)
like image 826
Chad Johnson Avatar asked Oct 05 '09 20:10

Chad Johnson


2 Answers

You will probably need to name your variable as "parameter3[]" for PHP's sake:

$.get('/controller/method/',
  {
    "parameter1": "value1",
    "parameter2": "value2",
    "parameter3[]": ["a","b","c"]
  },
  function(data) {
    if (data) {
    }
  else {
  }
});

$_GET["parameter3"] will appear in PHP as

Array
(
    [0] => "a"
    [1] => "b"
    [2] => "c"
)
like image 91
codehead Avatar answered Sep 18 '22 16:09

codehead


I've been down this road before. Join your array with a comma (or whatever character will work best for your scenario) and send it as a single parameter...

var arr = [5, "x", 25];
var parms = {
  parameter1: "value1",
  parameter2: arr.join(",");
}

And on the server-side, your "parameter2" post variable will look like 5,x,25

This is an easy solution for both sides of the wire.

like image 41
Josh Stodola Avatar answered Sep 16 '22 16:09

Josh Stodola