Search code examples
phpmysqlajaxkeyup

Ajax PHP - keyup function Bug (Slow Query)


I building a application to fetch records database with ajax. And I'm using the keyup function to catch what I'm querying/writing. But some times when I write something like "si" and there are many records in the database and query takes more time than me writing the next letter this bug happens. (querying 'sitre' but PHP only catches 'si'): enter image description here

My question is, is there a way to get around this? My JS code:

    <script>
$(document).ready(function(){
    load_data();
    function load_data(query) {
        $.ajax({
            url:"fetch.php",
            method:"POST",
            data:{query:query},
            success:function(data)
            {
                $('#result').html(data);
            }
        });
    }
    $('#search_text').keyup(function(){
        var search = $(this).val();
        if(search != '') {
            load_data(search);
        } else {
            load_data();
        }
    });
});
</script>

Thank you.

Fixed with delay thanks to Taron Saribekyan

<script>
var timeout = null;
$(document).ready(function(){
    load_data();
    function load_data(query) {
        $.ajax({
            url:"fetch.php",
            method:"POST",
            data:{query:query},
            success:function(data)
            {
                $('#result').html(data);
            }
        });
    }
    $('#search_text').keyup(function(){
        var search = $(this).val();
        clearTimeout(timeout);
        if(search != '') {
            timeout = setTimeout(function () {
            load_data(search);}
            , 500);
        } else {
            load_data();
        }
    });
});
</script>

Solution

  • Set delay before ajax query. See how to do it