Reputation: 85
Cancel all Ajax Request if search field is empty and if the search character length is < 3
$('#search-box').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
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);
}
}); // JSON request
}
}); // data bind
Upvotes: 0
Views: 354
Reputation: 36
From your code it's OK to use but what happens when second request finish after first request? for example first send "ab" and send "abc" later, the second result will be replace with the first. You can use abort() to abort the first connection before start the second one.
if(ajaxRequest){ajaxRequest.abort();}
ajaxRequest = $.ajax({
url: '...',
success: function(){
/* ... */
}
});
Upvotes: 1
Reputation: 8101
Use keyup event of search inputbox instead of section element.
$('#search').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
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);
}
}); // JSON request
}
}); // data bind
Upvotes: 0