Append not working properly on a Select after AJAX request

0

I need to make when completing the AJAX request jquery insert the options into a select When you do this the options do not appear when you click, however the inspect shows that they are present in select

Request script:

$(document).ready(function(){

        $.get("http://localhost/infinityy/assets/php/list-categories.php", function(data){
            categories  = JSON.parse(data);
            var select = $("#category");

            $(categories).each(function(){
                 var option = $("<option>");
                 option.attr("value", this.id);
                 option.text(this.name);
                 console.log(option);

                 select.append(option);

            });
        });

 });

Select:

<form  action="assets/php/add-category.php" method="post">
   <div id="form" class="form-group">
     <div class="form-group">
         <label>Categoria <a href="#" class="add-category"><i class="fa fa-plus" aria-hidden="true"></i></a></label>
         <select id="category" name="category" class="selectpicker" data-title="Categoria" data-style="btn-default btn-block" data-menu-style="dropdown-blue" required>

     </div>
   </div>
 </form>

Result even by clicking does not appear options

**WheninspectingSelect:**

    
asked by anonymous 15.01.2018 / 20:39

2 answers

1

When you add options dynamically or change the state of the select using select picker , you need to call a function that updates the element, add that line after adding the options.

$('.selectpicker').selectpicker('refresh');

More information: link

    
16.01.2018 / 16:21
1

The load function has documentation that can be viewed here .

It will load content within the parameter passed in it. An example with your case would be

Javascript:

$("#category").load("http://localhost/infinityy/assets/php/list-categories.php >", function () {
});

In php you make the query you do the same way, but instead of returning json, return the variable you want for a .php or .phtml view

HTML:

<?php foreach($opcoes as opcao): ?>
    <option value="<?php echo $opcao['valor']?>"> <?php echo $opcao['nome']; ?></option>
<?php endforeach; ?>

In this way, you will go through the $ options array that contains the value and name of your choice and fill in the html within your select.

    
15.01.2018 / 21:02