Sometimes you need to trigger an action based on keyup (or any other kind of key stroke action). Usually not a big deal to trigger an action on every key stroke, but if that action triggers an ajax call, you can have many ajax calls running if you’re a fast typer 🙂
So its a good idea to check to see if a previous ajax call is running, kill it, and start a new one with the updated value. This also avoids collisions and getting back expired data.
Its pretty simple. Assign a variable to your ajax/get call. Check for that variable before you do a call and use the .abort() method if it exists.
$('#input-id').keyup(function() {
run_autocomplete;
});
run_autocomplete = function() {
var val = $('#input-id').val();
if (ajaxRequest) { // if any previous ajaxRequest is running, abort
ajaxRequest.abort();
}
ajaxRequest = $.ajax({ // start new ajaxRequest
url: basePath+'/my/ajax/page',
type: 'post',
data: 'val='+val,
success: function(result) {
// handle successfull callback 'result'
// update autocomplete options
}
});
}