Foreach Ajax for combo

2

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

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

I would like to know if you have a new option for a select field that I set, using the Ajax result. For example: In HTML I have declared the select with no option, it would only be created from the result of that Ajax. Is it possible?

    
asked by anonymous 10.03.2016 / 15:00

1 answer

1

Return must be in 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 onchange function in the combobox.

    
10.03.2016 / 15:19