Mohan Ram Mohan Ram - 6 months ago 37
Javascript Question

How to bring ajax search onkeyup with jquery

My Script to call ajax

<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>


HTML

<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">


Question: while onkeyup i am using ajax to fetch the result. once ajax result delay increases problem occurs for me.

For Example
while typing
t
keyword i receive ajax result and while typing
te
i receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When i type
te
fastly. ajax search for
t
keyword come late, when compare to
te
. i dont know how to handle this type of cases.

Result
While typing
te
keyword fastly due to ajax delays. result for
t
keyword comes.

I belive i had expained up to reader knowledge.
Please help me in advance. Thank you.

Answer

You should check if the value has changed over time:

var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();

        if (value.length >= minlength ) {
            if (searchRequest != null) 
                searchRequest.abort();
            searchRequest = $.ajax({
                type: "GET",
                url: "sample.php",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});

EDIT:

The searchRequest variable was added to prevent multiple unnecessary requests to the server.

Comments