• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

131
Views
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

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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>

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error