Jason94
Jason94

Reputation: 13610

passing a array to php via ajax?

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?

Upvotes: 2

Views: 147

Answers (3)

Felix Kling
Felix Kling

Reputation: 816312

As mentioned in my comment, you should not use arrays this way. Only use arrays for numerical indexes:

Associative Arrays are not allowed... or more precisely you are not allowed to use non number indexes for arrays. If you need a map/hash use Object instead of Array in these cases because the features that you want are actually features of Object and not of Array. Array just happens to extend Object (like any other object in JS and therefore you might as well have used Date, RegExp or String).

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 = {};

it works

Upvotes: 3

JohnP
JohnP

Reputation: 50009

    $.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.

Upvotes: 1

xkeshav
xkeshav

Reputation: 54016

Read json_encode and json_decode

Upvotes: 1

Related Questions