Monday 18 April 2016

[Solved] Kill/abort previous requested URL in JQuery.

While we are using auto-suggestion in JQuery we are calling JQuery Post method and if an end user type quickly automatically other request goes to server.
Its panic for me, because if one request takes long time to execute other are be in queue and one by on all request goes to server, till the time there are
no suggestion on control seems. What i want, if we press key quickly and previous request are pending, quick kill/ abort previous request and make other fresh request
for fresh data.

I found something interesting on net, we got something called XMLHttpRequest, each Ajax or post method return it. And we can simple abort any XMLHttpRequest request by
calling .abort() method.

//define global request type
var xhr = new XMLHttpRequest();
function bindSuggestions() {
    $(".autosuggestion input[type=text]").typeahead({
        //hint: true,
        highlight: true,
        minLength: 3,
        source: function (query, process) {
            var strhint = "suggestion=" + this.$element.val();
    // kill previous request if xhr not null or undefined.
                if (xhr != null || xhr != 'undefined') {
                xhr = $.post("/handler/getJsonData", strhint, function (data) {
                    //process data

Know all about XMLHttpRequest on JQuery official page