Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
AJAX live search is super slow

Edit: Im using XAMPP with built in Apache, vscode

I make a live search input(html>js>php>js>html) , it run smoothly at first key-in, but it's getting slower and slower when i delete and key-in again , wonder what's causing the delay and how to fix it.

And i have a question, For this example , it is better to use jquery or pure javascript?

Thank you

html

<div>
   <input type="text" class="search" placeholder="find..." autocomplete="off" autocapitalize="characters">
   <div class="result"></div>
</div>

js

$(document).ready(function(){
    $(document).on("keyup input",".search",function(){

        var input = $(this).val();
        var result = $(this).next(".result");

        if(input.length){
            $.get("table.php", {term: input}).done(function(data){
                result.html(data);
            });
        } else{
            result.empty();
        }
    });
});

php

<?php

$link = mysqli_connect("localhost", "root", "******", "crypto");

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

if(isset($_REQUEST["term"])){

    $coin = "show tables from crypto where Tables_in_crypto LIKE ?";

    //prepare the statement
    if($prepare = mysqli_prepare($link, $coin)){

        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($prepare, "s", $param_term);
        
        // Set parameters
        $param_term = $_REQUEST["term"] . '%';
        
        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($prepare)){

            $result = mysqli_stmt_get_result($prepare);
            
            // Check number of rows in the result set
            if(mysqli_num_rows($result) > 0){
                
                // Fetch result rows as an associative array
                while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
                    echo "<p>" . $row["Tables_in_crypto"] . "</p>";
                }
            } else{
                echo "<p>no result</p>";
            }
        } else{
            echo "ERROR: $coin. " . mysqli_error($link);
        }
    }   
    // Close statement
    mysqli_stmt_close($prepare);
}
// close connection
mysqli_close($link);
?>
<script type="text/javascript" src="data.js"></script>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

JavaScript

  • Don't use "keyup input", use just the "input" Event.
  • Trim $(this).val().trim() your input values, you don't want an empty space to trigger a search for data!
  • Cooldown! You don't want to perform an additional AJAX ($.get()) request while one is already on the way. Instead create a setTimeout throttle which - only once the user stopped typing for N milliseconds the request will be triggered.
    A pseudocode logic to picture it is quite simple:
jQuery($ => { // DOM ready and $ alias in scope

  const search = ($input) => {

    const input = $input.val().trim();  // Trim your strings!
    const $result = $input.next(".result");

    if (!input) {
      $result.empty();
      return; // end it here
    }

    $.get("table.php", {term: input}).done((data) => {
      console.log(data); 
      // Exercise for the reader:
      // Make sure data is an Object
      // create "<p>" elements with text and populate $result
    });

  };

  let searchCooldown; // Search input cooldown

  $(document).on("input", ".search", function() {
    clearTimeout(searchCooldown); // clear occurring search timeout
    searchCooldown = setTimeout(() => {
      search($(this)); // will be triggered once user stops typing for 300ms
    }, 300); // 300ms seems like a good typing timeout?!
  });
});
  • No, you don't need jQuery. The Fetch API is mature enough.

PHP

  • Don't place <script> tags inside a PHP file — which its only job should be querying the data from a database and returning it.
  • Don't return HTML from PHP! That's a waste. You might want a PHP file to return JSON data instead - that way it can be used by your HTML page, your watch, fridge, etc. It's usually done using echo json_encode($result);. If you need to attach also an "error" property to your $result data JSON, do so.
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda