I have this array
var car = new Array();
car['brand'] = "Ford";
car['color'] = "red";
car['type'] = 1;
now, i tried sending this but php only tells me car is a undefined index:
$.post('regCar.php', { "car[]": car }, function(data) {
// some other lol here ...
});
Sending in "car[]": ["Ford", "red", 1] works fine :( How can i pass in an associative array to php?
3 Answers 3
As mentioned in my comment, you should not use arrays this way. Only use arrays for numerical indexes:
Associative
Arraysare not allowed... or more precisely you are not allowed to use non number indexes for arrays. If you need a map/hash useObjectinstead ofArrayin these cases because the features that you want are actually features ofObjectand not ofArray.Arrayjust happens to extendObject(like any other object in JS and therefore you might as well have usedDate,RegExporString).
This is exactly the reason why the code does not work.
Have a look at this fiddle: The alert is empty meaning that jQuery is not serializing (and therefore sending) any data at all.
One might expect that it would at least send an empty value, like car[]= but apparently it does not.
If you use an object:
var car = {};
Comments
Read json_encode and json_decode
4 Comments
car? Could you please post more of your code? Is car accessible from where you call $.post? What does console.log(car) just before the Ajax call give you? However, the problem could really be that you are using an array instead of an object.car does not work. The PHP functions will not help him here either.(削除)
$.post('regCar.php', {'car': car}, function(data) { // - I changed the key value name
});
You don't need to add the brackets in the data parameter (削除ここまで)
However, I recommend you use JS objects.
var car = {};
car.brand = "Ford";
car.color = "red";
car.type = 1;
If you're getting an undefined error on the PHP side, you'll need to post your PHP code.
EDIT
As @Felix Kling points out, dropping array in favor of objects will work for you.
print_r($_POST)and see what you get.