I’ve got a successful call going out to a coldfusion database controller using jQuery’s getJSON method. The returned information comes back in the format:
{
"COLUMNS": ["PRODUCT_HIERARCHY", "WEBPRODLINE", "POSITION", "FEATURES", "BENEFITS", "LINKS", "VIDEOS", "IMAGE_CUTAWAY", "MARKEDASNEW"],
"DATA": [
["23456689", "ProdName1", "A Feature 1", "A Benefit 1", "url", "vid_url", "img_name", "N"],
["234566891", "ProdName2", "A Feature 2", "A Benefit 2", "url", "vid_url", "img_name", "N"]
]
}
I now want to store the returned information as an object that I can then filter locally instead of making another call to the db. The problem is in the initializeView function. Here’s the relevant script:
$(document).ready(function() {
var productsFlag = false;
var enableLog = true;
var allProducts = $.getJSON(jsonURL, { method: "getAllProducts", returnformat: "json" }, function(data) {
productsFlag = true;
});
waitOnJson();
function waitOnJson() {
//this shows up in the log
logThis('areProductsReady?');
if (productsFlag) {
//this shows up in the log
logThis('productsFlags ready');
initializeProductView();
} else {
//this shows up in the log
logThis('productsFlags not ready');
t = setTimeout(waitOnJson, 100);
}
}
function initializeProductView() {
//this shows up in the log
logThis('initializeProductView');
//this displays [object Object]
alert(allProducts);
//this displays undefined
alert(allProducts.DATA);
$.each(allProducts.DATA, function(i, item) {
//this doesn't show up in the log
logThis(item[1]);
});
}
//as you can tell, this writes out to a debug console on the page
function logThis(eventString) {
if (enableLog === true) {
$('<p/>').append(eventString).appendTo("#log");
}
}
});
I’m sure that the problem is in my lack of understanding about what getJSON is returning but I’ve either had too much caffeine or not enough and I’m not seeing it. HELP!
Also, any thoughts on my blocking wait step? I want to be able to use the data in several different functions but I also need to wait for it to load before initializing the view.
First things first, you shouldn’t have to wait on the json response like you are. The function in your getJSON method call only returns when a response is received. When it does, it returns the results of your JSON call as the first argument of the method call. So you can just do something like this (I stripped a lot of your stuff out for simplicity sake):
Hopefully that clears things up somewhat.
EDIT: After reading your comment, if the alerts in your initializeProductView method are what you’re confused about, it’s probably because the getJSON method doesn’t return the result of the JSON AJAX request, it returns an jqXHR object. That’s why the .DATA attribute is undefined. If you did something to the effect of this, it would potentially work (assuming your returned JSON has a .DATA member):
Sorry about my misunderstanding earlier.