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 ?
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 post
ed to the server.
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".
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');
.
I just had the same issue, and here is a solution not mentioned in the comments so far:
$.ajax({
'url': 'my.php',
'type': 'POST',
'data': {
id: 1792,
arr[description_0] : 'very nice picture!', // DON'T quote the array key
arr[tags_0] = 'David "Nice Picture" 2010',
},
'success': function(response) {
alert(response);
}
});