- User clicks on search box
- User types a surname
- If the texbox lengh is more than 2 characters ajax webservice is called
The problem I have is with slow databases with thousands of records...
I can type "mcm" and wait and it will return 40 results in 3 seconds. I can continue to type "mcmil" and it will return 11 results in 1 second.
The problem is if I type "mcmil" all at once from scratch, i can visibly see the first 11 results then the results jump as the results for "mcm" and "mcmi" are loaded in, presumably as they are slower.
When the .keyup fires, I need a way to detect if a .ajax request is currently being made and cancel it before making the new one.
$('#employeesearchbox').keyup(function () {
    if ($("#employeesearchbox").val().length > 2) {
        $.ajax({
            type: 'POST',
            url: './webservices/Contacts.asmx/ContactsDirectorySearch',
            data: JSON.stringify({ Surname: $("#employeesearchbox").val() }),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (msg) {
                var employees = msg.d;
                $.each(employees, function (index, employee) {
                    $('#message').append("<li><a href='javascript:void(0);' class='response_object'>" + employee.Firstname + " " + employee.Department + "</a></li>");
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.error("The error was: " + xhr.responseText);
            }
        });
    }
});
I had a look at this post: abort-ajax-requests-using-jquery
It cancels the request directly after the .ajax where as i probably want to test on next key press and when i add this code i get "object undefined" error - as the object doesnt already exist!
please help
thanks
var xhr = $.ajax({
 ...
});
//kill the request
xhr.abort()
 
     
     
    