I use JSON.stringify method to pass an array to server.
I have an array that has 4 elements:
arr[10] = 1;
arr[20] = 1;
arr[30] = 1;
arr[40] = 1;
Then i do this:
arr = JSON.stringify(arr);
Then send it to the server:
jQuery.ajax({
type: "post",
url: baseurl+"profile/mprofile/action/ratings/add_ratings",
data:{"checkbox":checkbox,"review":review,"speciality":speciality,"arr":arr},
success: function(data, status) {
jQuery('#header-error').html(data);
}
});
I am getting the array in PHP with:
$arr = $this->ci->input->post('arr');
$arr = json_decode($arr);
print_r($arr) ; die ;
the result is
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] => 1
[11] =>
[12] =>
[13] =>
[14] =>
[15] =>
[16] =>
[17] =>
[18] =>
[19] =>
[20] => 1
[21] =>
[22] =>
[23] =>
[24] =>
[25] =>
[26] =>
[27] =>
[28] =>
[29] =>
[30] => 1
[31] =>
[32] =>
[33] =>
[34] =>
[35] =>
[36] =>
[37] =>
[38] =>
[39] =>
[40] => 1
)
Why is this happening?
That’s how javascript arrays work. When you set value to an index that is out of range, array is expanded, value is successfully set and all ‘missing’ values are set to
undefined.You are spoiled by PHP behaviour that blends the difference between arrays and dictionaries (or “associative arrays”, in PHP talk).
To avoid this behaviour, just create a dictionary in javascript instead of array.
Also, on PHP side you should pass
trueas a second parameter tojson_decode.This will make it return array instead of stdclass.