phpajaxtwitter-typeahead

How to populate Twitter Typeahead based on select box value?


I have an input text that is correctly populate with Twitter Typeahead. In this case i would like to select a value from select box and populate the input text with values that are related with selected dropdownlist value. I found similar questions about my doubt but unfortunatly i didnt get the correct way to solve this:

  1. Dynamically populating Twitter Bootstrap Typeahead
  2. Twitter bootstrap Typeahead to populate hrefs
  3. jQuery Autocomplete / Twitter Typeahead Populate Multiple Fields

Below is the code that display a select box that is populate with php code and an input text that is populated with Twitter TypeAhead script:

<!DOCTYPE html>
<html lang="en">
<head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">

<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>   

</head>

<body>

<div class="container">

<br>

<h1>DYNAMIC TWITTER TYPEAHEAD</h1>

<br>
<div class="row">

<?php 
    // Include the database config file 
    include_once 'dbConfig.php'; 

    // Fetch all the category data 
    $query = "SELECT * FROM categories ORDER BY category ASC"; 
    $result = $db->query($query); 
?>


<!-- category dropdown -->
<div class="col-md-4">
<select id="categoryFK" name="categoryFK" class="form-control">
    <option value="">Select category</option>
    <?php 
    if($result->num_rows > 0){ 
        while($row = $result->fetch_assoc()){  
            echo '<option value="'.$row['categoryID'].'">'.$row['category'].'</option>'; 
        } 
    }else{ 
        echo '<option value="">Category not available</option>'; 
    } 
    ?>
</select>
</div>

<div class="col-md-4">

<input type="text" name="products" id="products" class="form-control input-lg" autocomplete="off" placeholder="" />

</div>

</div>
</div>


</body>
</html>

Below is the script that call php script via Ajax:

<script>
$(document).ready(function(){

 $('#categoryFK').on('change', function(){
        var queryID = $(this).val();
 if(queryID){
 $('#products').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data: 'query='+queryID,
    dataType:"json",
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }
   })
  }
 });
 }
 });
});
</script>

And below is the php script (fetch.php) that populate values according to categoryID:


<?php
//fetch.php
include 'dbConfig.php';
if(!empty($_POST["query"])){ 
$request = mysqli_real_escape_string($db, $_POST["query"]);
$query = "
 SELECT * FROM products WHERE productName LIKE '%".$request."%' AND categoryFK = ".$_POST["query"]."
";

$result = $db->query($query); 
$data = array();

if(mysqli_num_rows($result) > 0)
{
 while($row = mysqli_fetch_assoc($result))
 {
  $data[] = $row["productName"];
 }
 echo json_encode($data);
}
}
?>

As i showed the code above, when i type something into input text after i selected any option into select box, the input text with Twitter TypeAhead just populate one register.

In this case, how can i improve php code above to populate input text with values related with select box value correctly? Thanks.


Solution

  • I managed to solve the problem. Below are the scripts that i modified to adapt on my project:

    AJAX

    <script type="text/javascript">
            var products;
            $ ( function ()
            {
                $('#categoryFK').on('change', function(){
                    var queryID = $(this).val();
    
                    $.ajax({
                        url:"fetch.php",
                        method:"POST",
                        data: {
                            category: queryID
                        },
                        dataType:"json",
                        success:function(data)
                        {
                            $("#products").val ('');
    
                            products = data;
                        }
                    });
                });
    
                $('#products').typeahead({
                    source: function ( query, result )
                    {
                        result ( $.map(products, function (item)
                            {
                                return item;
                            }
                        ));
                    }
                });
            });
            </script>
    
    

    And PHP script (fetch.php)

    <?php
    include 'dbConfig.php';
    
    if ( isset ( $_POST [ 'category' ] ) ) {
        $request = $db->real_escape_string($_POST["category"]);
    
        $query = "
            SELECT * FROM products WHERE categoryFK = ".$request."
        ";
    
        $result = $db->query($query);
        $data = array ();
    
        if ( $result->num_rows > 0 )
        {
            while($row = $result->fetch_assoc ())
            {
                $data[]=$row["productName"];
            }
    
            echo json_encode($data);
        }
    }
    ?>
    
    

    Now, with these modifications, i can select an option into "category" select box and after, type into input text where all valus related with selected option will be load :)