I have a text field where, as the user types, AJAX requests are sent to the server for a search to be performed and results returned:
<input type="text" class="form-control player-list-control-text" id="name" name="name" autocomplete="off" />
$('.player-list-control-text').keyup(function(){
get_player_list();
});
function get_player_list(){
$.ajax({
url: '/player/list/get',
data: {
'club_id' : $('#club_id').val(),
'position_id' : $('#position_id').val(),
'name' : $('#name').val(),
'page' : players_page,
'sort_by' : sort_by,
'sort_order' : sort_order,
},
type: 'POST',
success: function(result) {
if(result.hasOwnProperty('error'))
show_msg('error', result.error);
else
load_players(result);
},
error: function (response) {
handle_error(response);
}
});
}
The issue is, the search takes a second or two to execute, so when the user quickly types, say, 5 characters, the requests get all jumbled up and it either takes a very long time or it shows the wrong results - for example, the results of the 4-letter search instead of the results of the 5-letter search.
I could make sure the results of the last request sent are displayed by saving the request times on the client or preventing the user from typing while the previous request is being processed, but both seem like bad solutions - the first because it doesn't actually save the server any trouble and the second for the bad user experience.
What I'm really looking for is a way to interrupt the obsolete 4-letter search mid-execution on the server when the new, 5-letter search query is sent from the client.
Is this possible? How would I go about it?
The back-end script contains multiple queries since we have to search multiple tables if that's relevant at all.
EDIT: regarding the similar question that prompted a close vote, the solution there is not what I'm after. I want to interrupt server-side processing, not merely stop the request on the client.