My webpage uses ajax requests to fetch info of different items in my store. However, as of now, everytime you click an item (even the same item) it will reload the data, which is unnecessary as the data is somewhat static. So I tried to fix the problem like so;
var loaded = {}; //save loaded items in dictionary, so it is not necessary to load them again.
function loaditem(item){
if(item.text() in loaded){
postdata = {
item: item.text()
};
$.ajax({
type: "POST",
url: "iteminfo/fetch.php",
data: postdata,
dataType: "json",
success: function(data) {
loaddata(data);
loaded[item.text()] = data; //item.text() is the name of the item in this case
},
error: function() {
console.log('Something went wrong');
}
});
} else {
loaddata(loaded[item.text()]);
}
So to explain the function: the function gets item, which is iniated by html like so: <li onclick="loaditem($(this))">item</li>
. The function checks if the name of the item is in loaded
(key checking) and if it isn't, it will load the data and save it into loaded
.
Problem statement: however, when an item is clicked I get this error:
Uncaught TypeError: Cannot use 'in' operator to search for 'itemname' in undefined
So I searched the web, including StackOverflow, for an answer but I stumbled upon this answer which doens't even give a bloody answer (only an explanation) to the question! How can I access the global var 'loaded'
from my function?