Chad Johnson
Chad Johnson

Reputation: 21895

Pass arrays as parameters with 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)

Upvotes: 7

Views: 18390

Answers (4)

dano
dano

Reputation: 5630

It is possible to send any JSON object through a post command... even to an MVC controller. The difficult part is receiving the data... which you may need to deserialize manually at the server (either in the controller or with a JSON filter.

Upvotes: 0

codehead
codehead

Reputation: 2115

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"
)

Upvotes: 10

Josh Stodola
Josh Stodola

Reputation: 82483

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.

Upvotes: 1

Barnabas Kendall
Barnabas Kendall

Reputation: 4317

So first of all, I think you're mixing JavaScript and PHP syntax. This is probably what you meant to do to demonstrate passing arrays:

    $.get('foo.htm',
      {
        parameter1: 'value1',
        parameter2: 'value2',
        parameter3: [1, 2, 3],
        parameter4: {'one': 1, 'two': 2, 'three': 3}
      },
      function(data) {
        alert(data);
      });

Oddly enough JQuery doesn't like the nested object. It creates a query string like this:

 foo.htm?parameter1=value1
   &parameter2=value2
   &parameter3=1
   &parameter3=2
   &parameter3=3
   &parameter4=%5Bobject+Object%5D

For PHP passing back and forth complex objects, I recommend serializing your JavaScript object using a JSON stringify method and de-serializing it on the backend with json_decode.

Also, it appears you're using some MVC framework. If it's CodeIgniter and you're having trouble with GETs, consider using this postJSON helper method:

$.postJSON = function(url, data, callback) {
    $.post(url, data, callback, "json");
};

Upvotes: 0

Related Questions