kill all ongoing XHR requests
$('#search-box').keyup(function() { // bind the search data var input = $('.search-input').val();
$.getJSON({ // get JSON data
url: 'example/query.php?keyword=' + input,
//pre-load
beforeSend: function() {
$(".search-lists").html("<span class='loading'><img src='_/images/loading.gif' /></span>");
},
success: function(data) {
if (input.length >= 3) { // limit keyword to >=3
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li>';
output += '<a>' + val.term + '</a>';
output += '</li>';
});
output += '</ul>';
$('.search-results').html(output);
console.log('load ajax');
} // end if
else {
console.log('kill ajax');
}
}
}); // JSON request
}); // data bind
You have to do checking first, only than do filtering. Also I suggest using setTimeout
to reduce server calls:
<section id="search-box">
<form class="search-field">
<input id="search" class="search-input" type="text" value="Hello, I'm looking for..." />
</form>
<div class="search-results"></div>
</section>
var timer;
$('#search-box').keyup(function() { // bind the search data
clearTimeout(timer);
var input = $('.search-input').val();
if (input.length < 3) {
return;
}
timer = setTimeout(function () {
$.getJSON({ // get JSON data
url: 'http://test.sonsuzdongu.com/query.php?keyword=' + input,
//pre-load
beforeSend: function() {
$(".search-lists").html("<span class='loading'><img src='_/images/loading.gif' /></span>");
},
success: function(data) {
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
console.log('load ajax');
}
}); // JSON request
}, 300); //setTimeout
}); // data bind
To kill all request - you can try reloading page (requests will be terminated than). Or simply add some flag that indicates if you need to process further outputs or not.
success: function (data) {
if (!data.isEmptyObject()) {
// do processing.
}
}
There is an abort
method for cancelling the xhr request. You could use that as per your requirements.
just store the request like this, and then you can abort the request whenever you want.
var request = null;
....
....
function fetchJSON (){
if(request != null) {
request.abort();
}
request = $.getJSON({ // get JSON data
url: 'example/query.php?keyword=' + input,
//pre-load
beforeSend: function() {
$(".search-lists").html("<span class='loading'><img src='_/images/loading.gif' /></span>");
},
success: function(data) {
request = null;
if (input.length >= 3) { // limit keyword to >=3
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li>';
output += '<a>' + val.term + '</a>';
output += '</li>';
});
output += '</ul>';
$('.search-results').html(output);
console.log('load ajax');
} // end if
else {
console.log('kill ajax');
}
}
}); // JSON request
}); // data bind
}