Reputation: 2984
I'm having some problems with accessing JSON encoded PHP associative array. I get the JSON encoded array with $.get();
and assign it to data
variable.
$.get("includes/ajax/public.php", { do: "get-data", id: value },function(data) {
// NO DATA
if (!data || data == 'false') $('#noData').slideDown('slow');
// THERE IS DATA
else {
if ($('#noData').is(':visible')) $('#noData').hide();
$('#records').html(data.totalRecords);
console.log(data["totalRecords"]);
console.log(data);
}
});
This is what I get in console.
{"totalRecords":1,"data":[{"id":"1","country_id":"224", "name":"data name","address":"data address"}]}
I have to access totalRecords and also loop data array. However I can't access it.
console.log(data.totalRecords); //outputs undefined.
or
console.log(data['totalRecords']); //outputs undefined.
I could get rid off totalRecords part if I can count how many arrays there is in data
. data.length
doesn't work. It should give me just 1
but it gives me more than 100 which is not correct.
I just have to access totalRecords value (or just count how many arrays there is in it), and loop the data to manipulate DOM.
I would be glad if you could help me out with this small problem.
Upvotes: 0
Views: 152
Reputation: 174
You're accessing the totalRecords value like so:
data.totalRecords
it makes sense that it returns 1, since in the json the value of that field is indeed 1:
"totalRecords":1
You have to use the data field in order to acess the array of elements:
data.data
EDIT: You have to use $.getJSON() method so jQuery interprets it as a JSON and not just raw data.
http://api.jquery.com/jQuery.getJSON/
Upvotes: 1