I have a very simple function that loops through some JSON data and adds the data to a list:
function printData(file) {
$.getJSON('json/' + file, function(data) {
for( var i=0; i <= data.agencies.length; i++ ) {
$('#results').append(
'<li class="group">' +
'<div class="agency-logo"><img src="images/agency_logos/' + data.agencies[i].logo + '" alt="' + data.agencies[i].name + '" /></div>' +
'<div class="agency-info">' + data.agencies[i].name + '<br />' +
data.agencies[i].address + '<br />' +
data.agencies[i].city + ', ' + data.agencies[i].state + ' '+ data.agencies[i].zip + '<br />' +
data.agencies[i].phone + '<br />' +
data.agencies[i].email + '</div>' +
'<div class="agency-desc">' + data.agencies[i].description + '</div>' +
'</li>'
);
}
});
}
JSON data:
{
"agencies" : [
{
"name" : "Test Agency",
"address" : "283 Main Street",
"city" : "Danbury",
"state" : "CT",
"zip" : "06810",
"phone" : "(555) 555-5555",
"email" : "[email protected]",
"description" : "This is the description.",
"logo" : "logo.gif"
},
{
"name" : "Test Agency",
"address" : "100 Oak Street",
"city" : "Roseland",
"state" : "NJ",
"zip" : "06810",
"phone" : "(444) 444-4444",
"email" : "[email protected]",
"description" : "This is the description.",
"logo" : "logo.gif"
}
]
}
Everything is working and outputting as it should, however I am getting a console error on whatever is the first item that I am outputting: (I assume that I would get error on each call, but the JS stops being parsed at the error.)
TypeError: 'undefined' is not an object (evaluating 'data.agencies[i].logo')
This is my first time trying out outputting via JSON, so I am sure that I am missing something.