Reputation: 95880
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?
Upvotes: 24
Views: 98140
Reputation: 60556
Shortest version
$.post(url, { 'test[]': myArray });
Server side: $myArray = $_POST['test'];
Upvotes: 1
Reputation: 689
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'];
Upvotes: 6
Reputation: 301
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"
});
Upvotes: 17
Reputation: 13509
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'];
Upvotes: 3
Reputation: 179109
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'];
Upvotes: 43