Home Best way to handle Search in Ajax request
Reply: 1

Best way to handle Search in Ajax request

Ankit
1#
Ankit Published in 2018-01-13 09:33:59Z

I have search result on keyup event following is my code which if firing on keyup event

  function GetAllThirdParty(pageIndex, Type) {
    $.ajax({
        type: "POST",
        url: "ManageThirdParty.aspx/GetAllThirdParty",
        contentType: "application/json; charset=utf-8",
        data: '{Category: "' + $('#ddlCategoryFilter option:selected').attr('data-category') + '", pageIndex: ' + pageIndex + ', ' +
            'PageSize: ' + $('#ddlRecordsPerPage').val() + ', searchTerm: "' + SearchTerm() + '", Alphabate: "' + $('#hdnAlphabate').val() + '"}',
        beforeSend: function () {
            $('#tblThirdParty').dataTable().fnDestroy();
            $('#tblThirdParty > tbody').empty();
        },
        success: function (data) {
        }
    });
}

When I am typing slower the search result is perfect, but whenever I am typing faster(for same word) search result giving me wrong data because firingup GetAllThirdParty() without completing up current execution.

If I set timeout then search result giving me correct result but it takes lots of time to execute.

How to overcome this situation?

Ali Sheikhpour
2#
Ali Sheikhpour Reply to 2018-01-13 09:42:32Z

You have to name your ajax request and abort it on every call if exists before:

currentRequest = $.ajax({

           beforeSend:function(){
             if(currentRequest != null) {
                    currentRequest.abort();
                }
            },

        type: "POST",
        url: "ManageThirdParty.aspx/GetAllThirdParty",
        contentType: "application/json; charset=utf-8",
        data: '{Category: "' + $('#ddlCategoryFilter option:selected').attr('data-category') + '", pageIndex: ' + pageIndex + ', ' +
            'PageSize: ' + $('#ddlRecordsPerPage').val() + ', searchTerm: "' + SearchTerm() + '", Alphabate: "' + $('#hdnAlphabate').val() + '"}',
        beforeSend: function () {
            $('#tblThirdParty').dataTable().fnDestroy();
            $('#tblThirdParty > tbody').empty();
        },
        success: function (data) {
        }
    });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.33765 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO