I am trying to create an ajax search. I tried creating a fast loading php and another php pagecontaining the search form.
Search form:
<input id="searchtop" type="text" class="search-field" onkeyup="searchNotes()">
Search PHP link sample:
/searchform/?key=string
The searchNotes()
JS function:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
}, wait);
if (callNow) func.apply(context, args);
}
}
function searchNotes() {
var searcher = document.getElementById("searchtop").value;
if (searcher.length > 3) {
currentRequest = jQuery.ajax({
type: 'GET',
url: '/searchform/?key='+searcher,
cache: false,
success: function(data) {
$("#datafetch").html(data);
}
})};
}
var debounced = debounce(searchNotes, 50);
window.addEventListener('keyup', debounced);
issue: When I try typing for example "smooth" on the input fast, it works fine at first but then it loads all "smoot", "smoo", etc over the main "smooth" result and "smooth" is removed by jQuery('#datafetch').html('');
by the other incomplete strings.
I wanted to find a way to get the last string that is typed on input whithout the issue.