Armitage2k
Armitage2k

Reputation: 1254

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

Upvotes: 0

Views: 103

Answers (1)

mplungjan
mplungjan

Reputation: 177965

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>

Upvotes: 1

Related Questions