Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX - try to implement live search with debounce

I tried to implement AJAX live search with AJAX and I did it quite well. Then I tried to add the _.debounce function so it will not overloads the server but it didn't work well..

this is the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Live MySQL Database Search</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('.search-box input[type="text"]').on("keyup input", _.debounce(function(){
                /* Get input value on change */
                var term = $(this).val();
                var resultDropdown = $(this).siblings(".result");
                if(term.length){
                    $.get("backend-search.php", {query: term}).done(function(data){
                        // Display the returned data in browser
                        resultDropdown.html(data);
                    });
                } else{
                    resultDropdown.empty();
                }
            }),250);

            // Set search input value on click of result item
            $(document).on("click", ".result p", function(){
                $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                $(this).parent(".result").empty();
            });
        });
    </script>
</head>
<body>
<div class="search-box">
    <input type="text" autocomplete="off" placeholder="Search country..." />
    <div class="result"></div>
</div>
</body>
</html>

and this is the php file:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);

if(isset($query)){
    // Attempt select query execution
    $sql = "SELECT * FROM countries WHERE name LIKE '" . $query . "%'";
    if($result = mysqli_query($link, $sql)){
        if(mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_array($result)){
                echo "<p>" . $row['name'] . "</p>";
            }
            // Close result set
            mysqli_free_result($result);
        } else{
            echo "<p>No matches found for <b>$query</b></p>";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

// close connection
mysqli_close($link);
?>

Thanks!

like image 296
Dvir Naim Avatar asked Nov 27 '25 21:11

Dvir Naim


2 Answers

Your code doesn't include the Underscore library, so _.debounce() won't be available to use. That said, you can achieve what that method does quite easily by using a setTimeout() call:

var timeout;
$('.search-box input[type="text"]').on("keyup input", function() {
    var term = $(this).val();
    var $resultDropdown = $(this).siblings(".result");

    clearTimeout(timeout);
    timeout = setTimeout(function() {
        if (term.trim().length) {
            $.get("backend-search.php", { query: term }).done(function(data) {
                $resultDropdown.html(data);
            });
        } else {
            $resultDropdown.empty();
        }
    }, 250);
});
like image 180
Rory McCrossan Avatar answered Nov 30 '25 12:11

Rory McCrossan


you can do this by setting a setTimeout to make an ajax call on every change that occurs on input after passing a specific time but don't forget to kill the previous calls. you can use the code below to any function needs denounce.

var debounce;
$('#input').on('input', function (e) {
    clearTimeout(debounce);
    debounce = setTimeout( 
      function () { 
        searchText(e.target.value) 
      }, 1000
    );
});
like image 33
AleM Avatar answered Nov 30 '25 12:11

AleM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!