Foreach Ajax for combo

Asked

Viewed 1,255 times

2

I have the following Ajax snippet to feed text or select input with already defined values:

                ids.forEach(function (id) {
                    document.getElementById(id).value = dados[id];
                });

I wonder if you have how to create a new option for a field of type select I set, using the result of Ajax. For example: In HTML I have declared select with no option, it would only be created from the result of this Ajax. It is possible?

  • Yes, use Foreach or Each in conjunction with Append.

  • Could you give me an example of how to use append?

  • 1

    Okay, withdrawal quote.

1 answer

1


The return should be on json.

return json_encode($cidades)

JS

   var box_select = $('#cidades');
   var estado = $(this).val();

   $.ajax({
        dataType: 'json',
        url: urlBase + '/busca-cidades',
        type: "POST",
        cache: false,
        async: false,
        data: { estado: estado },
        success: function(data){
            if(estado != ''){
                box_select.html('');

                // Faz o ForEach
                $.each(data, function(i, val){
                    // Append tem a função de inserir
                    box_select.append("<option value='"+val.id+"'>"+val.nome+"</option>");
                });
            }
            else{
                box_select.html('');
            }
        }
    });

To call this AJAX do a function onchange on the combobox.

  • I did not understand why async false and cache false, xmlhttprequest synchronous is in disuse, and POST method does not cache.

  • I edited the question with your idea @Zoom.

  • @Zoom, solved the problem, thank you very much. I will edit the question with the answer.

  • @Guillhermenascimento cries a lot

  • Besides this loop with the jquery’s each method you can also use the JS for: for(var i in data){ box_select.append("<option value='"+data[i].id+"'>"+data[i].name+"</option>"); }

  • @Zoom what do you mean by that? It could be clearer, I’m just trying to give you a constructive criticism

Show 1 more comment

Browser other questions tagged

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