Append not working properly in a Select after AJAX request

Asked

Viewed 170 times

0

I need to make sure that when completing the requisition AJAX the jquery insert the options in a select but when doing so options do not appear when clicking but when inspecting shows that they are present in the 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 clicking does not show the options

inserir a descrição da imagem aqui

**When inspecting the Select: **

inserir a descrição da imagem aqui

  • Since you are using php, is it possible to do what you want with a load, it would be interesting for you? Or it has to be using append?

  • What would Load be?

  • Another javascript function to load options in another way. If this is a viable option, I can give you an answer explaining how to use this function.

  • I don’t know that function, could you show me?

2 answers

2


1

The function load has documentation that can be seen here.

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

Javascript:

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

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

HTML:

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

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

  • Since it’s in php I don’t think it would work for my case, because I’m making the user can dynamically add options by sending requests to the server

  • Know some other solution?

  • @Luhansalimena is possible to do using this function normally, every time a request is sent to the server, you run the load

Browser other questions tagged

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