23

Am wondering how to post an array using $.ajax. My array is something like this:

var a = new Array();
a['test'] = 1;
a['test2'] = 2;
and so on...

I tried:

$.ajax({
  url: baseUrl+"chat.php",
  data: { vars: a},
  type: 'post',
  success: function(data) {
alert(data);
}});

Any suggestions?

Martin G
  • 17,357
  • 9
  • 82
  • 98
Alec Smart
  • 94,115
  • 39
  • 120
  • 184

5 Answers5

43

Try this one:

var a = {};
a['test'] = 1;
a['test2'] = 2;

// or


var a = {};
a.test = 1;
a.test2 = 2;

// or


var a = {
    test : 1,
    test2 : 2
};

$.ajax({
  url: baseUrl+"chat.php",
  data: a,
  type: 'post',
  success: function(data) {
    alert(data);
  }
});

You may then access the data in your PHP script like this:

$_POST['test'];
$_POST['test2'];
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 1
    Is there a way to do this in the style of an `` element where the name field is `test[]` and the array indices are auto incremented? – Kevin_TA Jun 04 '12 at 17:41
  • 3
    @Kevin_TA, just use `{ test: ["array", "of", "values"] }` as the `data` argument for `$.ajax`. It will get serialized to `test[]=array&test[]=of&test[]=values`. – Ionuț G. Stan Jun 05 '12 at 15:04
  • "a" is an object, not an array in this example. Any ordering will be lost. – sivann Mar 01 '15 at 12:23
  • @sivann that's what the OP wanted. His `a` array is actually just an object. – Ionuț G. Stan Mar 01 '15 at 12:59
  • @IonuțG.Stan it's not an object, it says new Array(). Now if that solution was ok with him that's another matter :-) – sivann Mar 01 '15 at 18:46
  • @sivann it says `new Array`, but it's used like an ordinary object, i.e. `{}`. At that point you lose all ordering guarantees. http://stackoverflow.com/a/8067675/58808 – Ionuț G. Stan Mar 01 '15 at 19:35
16

I used this:

var newArray = new Array();
newArray.push("item1");
newArray.push("item2");
newArray.push("item3");

$.ajax({  
    type: "POST",
    url: urlToPost,
    data: JSON.stringify(newArray),
    contentType: "application/json"
   });
Aldo
  • 191
  • 1
  • 4
5

I prefer doing it this way:

ie.

var data = [{ name: 'test1', value: 'test data' }, { name: 'test2', value: 'test data' }];

$.ajax({  
    type: 'POST',
    url:  'url',
    data: data,
   });

Server side (PHP): $_POST['test1']; $_POST['test2'];

Tom
  • 679
  • 1
  • 12
  • 29
3

Here is an example how I pass arrays (from real-life code) :

$.ajax({
  type: 'POST',
  url: url,
  data: { CartID : cartID, 'Manufacturers[]' : manufacturers, 'PartNumbers[]' : partNumbers },
  success: function(res)
  {
    ...
  },
  dataType: "json",
  async: false
});

then on the server-side:

$cartID = $_POST['CartID'];
$manufacturers = $_POST['Manufacturers'];
$partNumbers = $_POST['PartNumbers'];
nightcoder
  • 13,149
  • 16
  • 64
  • 72
1

Shortest version

$.post(url, { 'test[]': myArray });

Server side: $myArray = $_POST['test'];

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149