I want to use AJAX to get a list of Styles from my database. The Styles have a Category FK that I want to use to sort the Styles into a JSON object and then use that JSON with JavaScript to populate a Select list based on the Category chosen by the user.
Here is my code:
$(document).ready(function () {
var styles = {
"cat1": [],
"cat2": [],
"cat3": [],
"cat4": []
}
$.getJSON("/Inventory/GetStyles", function (data) {
$(data).each(function (i, d) {
var n = {
"StyleID": d.StyleID,
"Name": d.Name,
"CategoryID": d.CategoryID
};
switch (d.CategoryID) {
case 1:
styles.cat1.push(n);
break;
case 2:
styles.cat2.push(n);
break;
case 3:
styles.cat3.push(n);
break;
case 4:
styles.cat4.push(n);
break;
};
});
});
alert(styles.cat1[0].Name);
});
When I use debugger;
and step through, I see that everything seems to be working just fine. styles
is filled with data as expected but the alert never goes off. Instead, I get an error:
TypeError: styles.cat1[0] is undefined
This is confusing because, when debugging, I can mouse over and see that styles.cat1[0].Name
has the value it should. Oddly, however, this only works when I put the debugger;
statement inside my AJAX call, as seen here:
If I move the debugger;
statement to outside the AJAX call, the styles.cat1[0].Name
changes to undefined, as seen here:
I am at a loss as to how to get this straight. Any help is greatly appreciated.