Editar: estoy usando XAMPP con Apache incorporado, vscode
Hago una entrada de búsqueda en vivo (html>js>php>js>html), funciona sin problemas en la primera entrada, pero se vuelve cada vez más lenta cuando elimino y vuelvo a teclear, me pregunto qué está causando la demora y cómo arreglalo.
Y tengo una pregunta, para este ejemplo, ¿es mejor usar jquery o javascript puro?
Gracias
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>JavaScript
"keyup input" , use solo el Evento "input" .$(this).val().trim() tus valores de entrada , ¡no quieres un espacio vacío para activar una búsqueda de datos!$.get() ) mientras ya hay una en camino. En su lugar, cree un acelerador setTimeout que, solo una vez que el usuario dejó de escribir durante N milisegundos, se activará la solicitud. 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?! }); });PHP
<script> dentro de un archivo PHP, cuyo único trabajo debería ser consultar los datos de una base de datos y devolverlos.echo json_encode($result); . Si necesita adjuntar también una propiedad de "error" a su JSON de datos de $result , hágalo.