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?
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'];
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" });
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'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With