Hey Guys, javascript newb here. I’m attempting to create a type of Ajax search function which will query a db and draw out a table. That much I have working correctly.
The only problem was queries were done on the keystroke, which would cause issues when several Ajax replies would come back, but out of order. Meaning, sometimes the latest Ajax response wouldn’t be the last thing typed. So, I attempted to create a type of ‘cache’ which would be a 2D associative array with the first index the search query (i.e. cache[‘search string’]) would would be an array of just a time stamp and the Ajax response. (i.e. cache[‘search string’][‘ts’] and cache[‘search’][‘c’]) I then would go through this array, find the most recent search query and display that content. The problem is, when I debug the code through firebug I am seeing indexes in cache of ‘c’ and ‘ts’. These be directly in cahce there, but within an [B]element
So anyway, I know there are some ways around this (use an object, don’t search on keystroke), but I’d like to get a better understanding of javascript. This is basically an exercise for me.
Here’s the code, I’m using the prototype library:
[CODE]
var oldSearchCC = ”;
var oldSearchName = ”;
var cache = new Array();
var ct = new Date();
Event.observe(window,’load’,function() {
$(“searchName”).value = “”;
$(“searchCC”).value = “”;
$j(“#courselisting”).tablesorter({sortList: [[2,0]]});
//tablesorter overrides onclick
Event.observe(“searchName”,”click”,function()
{
$(“searchName”).focus();
});
Event.observe(“searchCC”,”click”,function()
{
$(“searchCC”).focus();
});
Event.observe(“searchName”,”keyup”,function()
{
var time = new Date();
if (typeof cache[$F(“searchName”)] != “undefined”)
{
cache[$F(“searchName”)][‘ts’] = time.getTime();
reDisplay();
}
else
{
cache[$F(“searchName”)] = new Array();
cache[$F(“searchName”),’ts’] = time.getTime();
cache[$F(“searchName”),’c’] = ”;
ajaxSearch(‘name’,$F(“searchName”));
}
});
Event.observe(“searchCC”,”keyup”,function()
{
if ($F(“searchCC”) != oldSearchCC)
{
q = $F(“searchCC”).stripTags();
ajaxSearch(‘course_code’,q);
oldSearchCC = q;
}
});
});
function ajaxSearch(column,query)
{
new Ajax.Request(base_url+’maint/ajaxSearch’, {
method: ‘get’,
parameters: ‘c=’+column+’&q=’+query,
onComplete: function(transport)
{
updateCache(transport,query);
}
});
}
function updateCache(transport,query)
{
cache[query,’c’] = transport.responseText;
reDisplay();
}
function reDisplay()
{
var latestTs = 0;
var latestContent = ”;
for(var index in cache)
{
if (cache[index,’ts’] > latestTs) {
latestTs = cache[index,’ts’];
latestContent = cache[index,’c’];
}
}
$(‘tableBody’).innerHTML = latestContent;
}
Any suggestions will be helpful! ?