PHP Jquery dynamic autocomplete

Asked

Viewed 601 times

-1

I am developing a php registration page where it contains 2 fields, a dropdownlist select field whose name is "Category" and the other an input field with autocomplete functions whose name is "Product".

What I would like to do, if possible, is that when selecting a category in the dropdownlist, the input autocomplete field automatically loads records related to the selected category in question.

For example, if the "Butcher" category is selected, the autocomplete input field would only load the products related to the "Butcher" category when the product name is entered in the autocomplete input.

I have researched here some similar doubts, but I was not successful in finding a solution to this question:

  1. Jquery Autocomplete
  2. Autocomplete + PHP + MYSQL
  3. Autocomplete Type
  4. Autocomplete in dynamic fields

Below follows the code I use. This code contains the php code to load the categories, which in this case loads correctly, and the other part the input field that also loads the records correctly, but I can’t find a way to put these fields as dynamic:

<body>

<div class="container">
<br>
<form method="post">
<div class="row">
<div class="col-md-4">
    <label>Selecione a categoria</label>

<?php

include 'db.php';
$stmt = $connection->prepare('SELECT * FROM categorias');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<select name="categoriaFK" id="categoriaFK" class="form-control">
  <?php foreach($results as $row): ?>
    <option value="<?= $row['categoriaID']; ?>"><?= $row['categoria']; ?></option>  
<?php endforeach ?>
</select>

</div>

<div class="col-md-4">
    <label>Digite o produto</label>
    <input type="text" class="form-control" id="produtos"/>
</div>
<div class="col-md-4">        
    <input type="submit" class="btn btn-success btn-block mt-4" name="submit" value="SUBMIT"/>
</div>
</form>

</div>
</div>
<script>
$(function() {
    $("#produtos").autocomplete({
        source: "search.php",
    });
});
</script>

</body>

In the case, as stated above, how can I improve the above code to streamline the two fields in question (category) and (products)? Thank you.

2 answers

0


Create an array of your products. When you have a change in category value you change your autocomplete to the specific array of that category.

Example (I took the query to the bank to create the arrays in hand):

<header>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
</header>
<body>

<div class="container">
<br>
<form method="post">
<div class="row">
<div class="col-md-4">
    <label>Selecione a categoria</label>

<?php

//include 'db.php';
//$stmt = $connection->prepare('SELECT * FROM categorias');
//$stmt->execute();
//$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

$results = array(array("categoriaID"=>0,"categoria"=>"Acougue"),
array("categoriaID"=>1,"categoria"=>"Padaria"),
array("categoriaID"=>2,"categoria"=>"Farmacia"),
);

$Produtos = array();
//array de produtos do Acougue
$Produtos[0]= array("Carne","Frango","Coracao");
//array de produtos do Padaria
$Produtos[1]= array("Pao","Baguete","Biscoito");
//array de produtos do Farmacia
$Produtos[2]= array("Pilula","Xarope","Pasta de Dente");


?>

<select name="categoriaFK" id="categoriaFK" class="form-control">
  <?php foreach($results as $row){ ?>
    <option value="<?= $row['categoriaID']; ?>"><?= $row['categoria']; ?></option>  
<?php  }?>
</select>

</div>

<div class="col-md-4">
    <label>Digite o produto</label>
    <input type="text" class="form-control" id="produtos"/>
</div>
<div class="col-md-4">        
    <input type="submit" class="btn btn-success btn-block mt-4" name="submit" value="SUBMIT"/>
</div>
</form>

</div>
</div>
<script>
$(function() {
    var availableTags =[];
    <?php 
    foreach ($Produtos as $chave=>$categoria){
        echo "availableTags[".$chave."]= [";
        foreach ($categoria as $prod){
            echo '"'.$prod.'",';
        }
        echo "];".PHP_EOL;
    }

    ?>

    $("#categoriaFK").change(function(){
        $("#produtos").autocomplete({
            source: availableTags[$("#categoriaFK").val()],
        });
    });


});
</script>

</body>

If it is too big the list of products and do not want to leave them all pre loaded on the page. Do an ajax on the onchange of select and always change the value of the same variable. Remember that in this case it would be good to put a loading on the page, because it will only update the list when you finish the ajax.

  • Hello Fabrício. Thank you for your feedback. Based on your explanation I made some adaptations to the code and arrived at the solution. I also got answers in Stack in English which in fact also matches what you mentioned here. Follow the link (https://stackoverflow.com/questions/59614107/how-to-populate-twitter-typeahead-based-on-select-box-value). Thank you :)

-2

exactly as in the answer above, it is as if js would perform this search for the database where you would save the categories predefined by you in the database or some similar system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.