Quantcast
Channel: VBForums - jQuery
Viewing all articles
Browse latest Browse all 69

[RESOLVED] jQueryUI - Autocomplete

$
0
0
I currently have a PHP file that is returning the JSON equivalent of some rows returned from a database, for what its worth, here is the PHP file:
Code:

<?php
  $configs_database = include('config_database.php');

  // Database variables
  $dbHost = $configs_database['host'];
  $dbUsername = $configs_database['username'];
  $dbPassword = $configs_database['password'];
  $dbName = $configs_database['name'];

  /* Create connection */
  $dsn = "mysql:dbname=$dbName;host=$dbHost;charset=utf8mb4";
  $db = new PDO($dsn, $dbUsername, $dbPassword);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

  // Search for
  $stmt = $db->prepare("SELECT `customer`.`household_id`, `customer`.`first_name`, `customer`.`last_name`, `suffix`.`suffix`, `customer`.`phone`, `customer`.`email`
                        FROM `customer`
                        INNER JOIN `suffix` ON `suffix`.`suffix_id` = `customer`.`suffix_id`;");
  $stmt->execute();
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  $json = [];
  // Iterate through each row
  foreach ($rows as $row) {
    $customer = new stdClass();
    $customer->label=implode(' ', [$row['first_name'], $row['last_name'], $row['suffix'], format_phone($row['phone']), $row['email']]);
    $customer->value=$row['household_id'];

    array_push($json, $customer);   
  }

  // Return the array encoded as JSON data
  echo json_encode($json);
 
  function format_phone($phone) {
    if(preg_match( '/^(\d{3})(\d{3})(\d{4})$/', $phone,  $matches )) {
        $phone = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
    }
    return $phone;
  }
?>

Then in my jQuery that runs at the bottom of my webpage, I have the following code:
Code:

$(document).ready(function(){
  // Get the autocomplete label/value pairs
  var autocomplete_source = [];
  $.get("php/autocomplete_source.php", function(data){
    autocomplete_source = jQuery.parseJSON(data);
  });

  //Auto complete the quick_search input
  $('#quick_search').autocomplete({
    source: autocomplete_source,
    minLength: 3,
    select: function( event, ui ) {
      // Debugging, simply alert what was selected
      alert("Selected: " + ui.item.label + " Household ID: " + ui.item.value );
    }
  });
});

I verify that the JSON is being returned in the $.get function, but whenever I start typing and get past my 3rd character I get "No search results.".

Viewing all articles
Browse latest Browse all 69

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>