The following is returning ‘undefined’ as the value for each item. Can someone show me why?
Jquery
$("button").click(function () {
var estimateID = this.id;
var baseURL = "/Dashboard/EstimateDetails/";
var url = baseURL + estimateID;
$.getJSON(url, function (data) {
for (var i = 0; i <= data.details.length; i++) {
$('#Details').html("<p>item1=" + data.details.Dma + " item2=" + data.details.Callsign + " item3=" + data.details.Description + "</p>");
}
});
JSON
{
"details": [{
"Dma": "Albany-Schenectady-Troy",
"CallSign": "WRGB",
"Description": "WRGB (CBS) Schenectady"
}, {
"Dma": "Albany-Schenectady-Troy",
"CallSign": "WTEN",
"Description": "WTEN (ABC) Albany "
}, {
"Dma": "Albany-Schenectady-Troy",
"CallSign": "WXXA",
"Description": "WXXA (Fox) Albany "
}, {
"Dma": "Atlanta",
"CallSign": "WGCL",
"Description": "WGCL (CBS) Atlanta "
}, {
"Dma": "Atlanta",
"CallSign": "WXIA",
"Description": "WXIA (NBC) Atlanta "
}, {
"Dma": "Austin",
"CallSign": "KXAN",
"Description": "KXAN (NBC) Austin "
}, {
"Dma": "Austin",
"CallSign": "KVUE",
"Description": "KVUE (ABC) Austin "
}, {
"Dma": "Baltimore",
"CallSign": "WMAR",
"Description": "WMAR (ABC) Baltimore "
}, {
"Dma": "Baltimore",
"CallSign": "WBAL",
"Description": "WBAL (NBC) Baltimore"
}, {
"Dma": "Baltimore",
"CallSign": "WJZ ",
"Description": "WJZ (CBS) Baltimore "
}, {
"Dma": "Baltimore",
"CallSign": "WBFF",
"Description": "WBFF (Fox) Baltimore "
}]
}
EDIT – the result when I run the above code is a single line of HTML added to the details div as follows:
item1=undefined item2=undefined item3=undefined
data.details.Callsignis wrongdata.details[i].Callsignis what you want, i.e. you are missing the array index as you loop over
details. Notice you are doing that for multiple variables.Cleaner code might help. Separating the variables out like so is a good start…
Is much more readable, and less error prone IMHO.
EDIT — as pointed out in comments,
htmlwill overwrite the content of your div each time in the loop. You probably wantappendinstead.