I'm trying to utilize HTML5 sessionStorage to retain some data previously retrieved from an external API, so as to cache the data when it is later called again, rather than making a connection to retrieve redundant data that has already been retrieved this session.
function getItemWithTooltip(item_id, div_id) {
var xmlhttp2 = new XMLHttpRequest();
var url2 = "https://api.guildwars2.com/v2/items/"+item_id;
xmlhttp2.onreadystatechange=function() {if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {parseItemTooltip(xmlhttp2.responseText);}};
xmlhttp2.open("GET", url2, true);
//xmlhttp2.send();
var item;
var cache_enabled = true;
// Cache results for quicker page loads
if (cache_enabled == true){
if (Storage !== void(0)) {
// Retrieve data (if stored)
if (sessionStorage[String(item_id)]) {
//item = JSON.parse(sessionStorage.getItem(String(item_id)));
item = JSON.parse(sessionStorage[item_id.toString()]);
//window.alert("sessionStorage: Retrieved");
//alert(typeof (item));
//alert(item);
}
}
}
if (item == null){
xmlhttp2.send();
}
function parseItemTooltip(response) {
//var item = JSON.parse(response);
if (item == null){
// Store data
if (cache_enabled == true){sessionStorage.setItem(item_id.toString(), JSON.stringify(response));}
//sessionStorage.setItem(String(item_id), item);
//if (cache_enabled == true){sessionStorage.setItem(String(item_id), response);}
//window.alert("sessionStorage: Stored");
item = JSON.parse(response);
}
//..More code here that was not relevant and removed to save space..
}
}
Well after bugging-out at my code for another hour, I finally figured out the issue, and it was something stupid simple, like it usually is.
My answer was to reverse these two lines:
To this:
Reasoning: It was trying to fill in the div before it was being created. Previously it didn't matter, because it was filled in while waiting for the remote server response, however now with data cached into sessionStorage, it was retrieved so fast, that the order did become a factor. Always good to pay attention to logical order of progression.
Thank you to everyone who contributed to debugging this. Much thanks, and appreciation! Quick responses, and friendly people. Made for a great time for a first-timer on this website.