Alec Smart Alec Smart - 3 months ago 9
jQuery Question

jQuery post array

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?

Answer

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'];