JQuery UI Autocomplete slow selecting an element

454 views Asked by At
<script type="text/javascript">
$(function() {
$( "#customers" ).autocomplete({
source: 'search.php'
});
});
</script>
<div class="ui-widget"><input id="customers" name="Cno" placeholder="Customer Name"></div>

search.php

<?php include('header.php');
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM customers WHERE Customer_Name LIKE '%".$searchTerm."%' ORDER BY Customer_Name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['Customer_Name'];
}
//return json data
echo json_encode($data);
?>

For Some arrays it was not working fine as I described in Jquery UI not working properly for some words And I added this code

$mysqli->set_charset('utf8mb4') 

Then I faced issue in selecting element from dropdown, it takes too long to convert li class to ui-state-active, How to solve it?

Any help would be great!

1

There are 1 answers

0
Twisty On

In regards to your PHP, I would advise:

PHP

<?php
  include('header.php');
  //get search term
  $searchTerm = $_GET['term'];
  $data = array();
  //get matched data from skills table
  $query = $db->prepare("SELECT * FROM customers WHERE Customer_Name LIKE '%?%' ORDER BY Customer_Name ASC");
  $query->bind_param('s', $searchTerm);
  $query->execute();
  $results = $query->get_result();
  while ($row = $results->fetch_assoc()) {
    $data[] = $row['Customer_Name'];
  }
  $query->close();
  $db->close();
  //return json data
  header('Content-Type: application/json');
  echo json_encode($data);
?>

This will help protect your scripts from SQL Injection.

In regards to your jQuery, I would advise:

JavaScript

$(function() {
  $("#customers").autocomplete({
    minLength: 3,
    source: 'search.php'
  });
});

If you enter 'sim', the autocomplete will send this to your PHP via GET. The response will be something like:

[
  "Bart Simpson",
  "Homer Simpson",
  "Lisa Simpson",
  "Maggie Simpson",
  "Marge Simpson"
]

In your console, you should see this activity and can review the execution time. This will tell you how long the PHP is taking to provide a response to the request. This data should load in the autocomplete right away.

If you are seeing slowness, you will have to determine if it's in your PHP or JavaScript. That will determine where to look for issues.