Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
Ajax array result as Select option - undefined

I am new to AJAX / JSON, and am struggling to parse an AJAX array response into a <select> dropdown.

My result looks fine, but even though I researched quite a few tutorials online and tried various ways of returning the result, every single one of them results in the dropdown menu options showing as undefined.

AJAX result

[{"property_code":"AGGCO","name":"Office Name"}]

Note: there may be as many as 100 entries in the array.

jQuery

$('#unit').on('change', function() {
    var unitID = $(this).val();
    if (unitID) {
        $.ajax({
            type: 'POST',
            url: '../../controllers/admin_addNewUser_units_offices.php',
            data: 'action=unit_office_dropdown&unit_id=' + unitID,
            success: function(response) {
                console.log(response);
                var len = response.length;

                $("#office").empty();
                for (var i = 0; i < len; i++) {
                    var code = response[i]['property_code'];
                    var name = response[i]['name'];

                    $("#office").append("<option value='" + code + "'>" + name + "</option>");

                }
            }
        });
    } else {
        $('#office').html('<option value="">Select Business Unit first</option>');
    }
});

Could someone explain what I am doing wrong please? Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code looks reasonable - assuming you parse the JSON

It can be simplified

NOTE: If you want "Please select", you can use .html() which will empty the select too - if you do not empty, then next time, you will have the new options added to the previous ones

const response = `[{ "property_code": "AGGCO", "name": "Office Name"}]`; // for testing
const opts = JSON.parse(response); // not needed if you deliver application/json

$("#office")
  .html(new Option("Please select", ""))
  .append(opts
    .map(({ property_code, name }) => new Option(name, property_code)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="office"></select>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda