views:

68

answers:

4

I would like to send data using $.ajax like this:

$.ajax({'url': 'my.php',
        'type': 'POST',
        'data': arr,
        'success': function(response) {
                      alert(response);
                   }
});

The problem is that arr is an associative array that looks like:

arr['description_0'] = 'very nice picture!';
arr['tags_0'] = 'David "Nice Picture" 2010';
arr['description_1'] = 'In the pool';
arr['tags_1'] = '"April 2010" Australia';
    .                    .
    .                    .
    .                    .

If my.php looks like:

<?php
echo count($_POST);
?>

The response is 0.

But, if I change

'data': arr,

to

'data': 'a=chess&b=checkers',

the response is 2, as expected.

What should I convert arr to so that the data will be sent properly ?

+1  A: 

if you're really having problems on that, try reading $.param().


also, I've discovered, how did you initialize your arr variable?

you should initialize it as var arr = {}; then pass it as 'data': arr,. Try to look at firebug or webket's dev tools to see what data are being posted to the server.

Reigel
A: 

Refer to this link.

I post a function that will pass javascript array to PHP as is.

Hope it helps.

Manie
A: 

Another option is to serialize to JSON and the deserialize JSON on the server:

http://code.google.com/p/jquery-json/

data: $.toJSON(arr)

Note: You do not need to quote the keys in the $.ajax({url: ..., data: ...})

Also you should really use an object as there is not an associative array in JavaScript. JavaScript arrays are intended to use numeric "keys".

johans
A: 

AJAX data is really just a regular GET or POST request done "silently" by Javascript. As such, the data has to be formed as a normal GET or POST, which means it has to be in key=value format. Your 'data' = arr is a value, but has no key, so PHP cannot assign it to $_POST automatically. As far as PHP is concerned, it just receives a long string of text.

You can retrieve the data by reading $HTTP_POST_RAW_DATA, if your PHP's configured to set that, or via $data = file_get_contents('php://input');.

Marc B