views:

6825

answers:

2

Hi,

in my app i need to send an javascript Array object to php script via ajax post. Something like this:

var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
alert(saveData);
$.ajax({
    type: "POST",
    url: "salvaPreventivo.php",
    data:saveData,
    async:true
    });

Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work.

Ideas?

Thanks in advance

+6  A: 

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

Paolo Bergantino
Thanks, it works this way ;)
Alekc
+1  A: 

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
dbarker
$.ajax() will stringify a js object (map) by default. check out the processData option!
zack