Reputation: 13
I have an array that I can't access the data of.
$.get("url"), function(data) {
console.log(data);
}
Console output:
Array(
[0] => Array ( [element0] => 1 [element1] => value1 [element2] => value2 )
[1] => Array ( [element0] => 2 [element1] => value1 [element2] => value2 )
)
Now I'm trying to access the elements with data[0], data[0]["element0"] and what not, but I either get nothing or it returns the characters at that position instead of the data. How do I access the elements properly?
Upvotes: 0
Views: 54
Reputation: 121
It looks like you are using PHP to output your data. PHP and JavaScript cannot communicate with each other. They 'speak' different languages. You have to find a way for those two scripts to get along. I recommend you to encode your PHP array to a JSON string.
//PHP
header("Content-type: application/json; charset=utf-8");
$data = array(
array(
'element0' => 1,
'element1' => 'value1',
'element2' => 'value2',
),
array(
'element0' => 1,
'element1' => 'value1',
'element2' => 'value2',
),
);
echo json_encode($data);
JavaScript can decode JSON, since you are using jQuery to make your XHR request, jQuery will automatically decode the JSON to a JavaScript object because we set the JSON headers.
$.get("url"), function(data) {
console.log(data[0].element1); //gives output: 'value1'
}
Good luck!
Upvotes: 1