In the below code I am using ajax to obtain all data from the database and store it in the proj4_data variable. The variable is global. I am able to access the value of the variable when I click on a button on the page, but when I try to access the variable value right after callback function is done loading, the value of the variable is empty (the alert is where I try to get the value). Can someone help tell why this is happening:
$(document).ready(function() {
var modal = document.getElementById('myModal');
var prod_name = document.getElementById('product_name');
cart = new shopping_cart("jadrn026");
proj4_data = new Array();
$.get('/perl/jadrn000/proj4/get_products.cgi', storeData);
alert(proj4_data);
$('#milk').on('click', function() {
tmpString = "";
var value = $("#milk").val();
prod_name.innerHTML = value;
tmpString += '<ul id="db_items">';
for(var i=0; i < proj4_data.length; i++) {
if(proj4_data[i][1] == "Milk chocolate") {
var str1 = proj4_data[i][2].split("'").join("\\'");
var str2 = proj4_data[i][3].split("'").join("\\'");
var str3 = proj4_data[i][4].split("'").join("\\'");
tmpString += "<li><button class=\"description\" onclick=\"showDesc(\'" + str1 + "\', \'" + str2 + "\', \'" + str3 + "\', \'" + proj4_data[i][0] + "\', \'" + proj4_data[i][6] + "\')\"><img src=\"/~jadrn000/PROJ4_IMAGES/" + proj4_data[i][0]+".jpg\" alt=\""+ proj4_data[i][2]+"\""+
" width=\"200px\" /></button><br />";
tmpString += "<p id='price'>$" + proj4_data[i][6] + "</p>";
tmpString += "<input type='button' value='Order' onclick=\"showDesc(\'" + str1 + "\', \'" + str2 + "\', \'" + str3 + "\', \'" + proj4_data[i][0] + "\', \'" + proj4_data[i][6] + "\')\"" + proj4_data[i][0]+"' />";
}
}
tmpString += "</ul>";
var handle = document.getElementById('content');
handle.innerHTML = tmpString;
});
function storeData(response) {
var tmpArray = explodeArray(response,';');
for(var i=0; i < tmpArray.length; i++) {
innerArray = explodeArray(tmpArray[i],'|');
proj4_data[i] = innerArray;
}
}
// from http://www.webmasterworld.com/forum91/3262.htm
function explodeArray(item,delimiter) {
tempArray=new Array(1);
var Count=0;
var tempString=new String(item);
while (tempString.indexOf(delimiter)>0) {
tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
Count=Count+1
}
tempArray[Count]=tempString;
return tempArray;
}