Asynchronous loading of select list options

I’m retrieving information on Municipality names, ZipCodes, etc. from a public service provider (DAWA) using AJAX. At first I had an issue retriving the data until I made the transfer asyncronous, thus ajaxGetMunicipalitiesFromDAWA is an asyncronous function. I have checked ajaxGetMunicipalitiesFromDAWA and it loads data correctly.

The I try to update my selectlist using the data, but it seems the update occurs before Municipalies is loaded. I have tried to make loadMunicipalities asyncronous as well, but still I end up having an empty option list.

Please help

HTML code:

<div class="row mt-3 fw-bold">
    <div class="col-3"><label asp-for="PostalAddress_Municipality">Municipality:</label></div>
    <div class="col-9">
        <select asp-for="PostalAddress_MunicipalityId" class="form-control form-control-sm" name="municipality"></select>


    var Municipalities = ajaxGetMunicipalitiesFromDAWA();
async function ajaxGetMunicipalitiesFromDAWA() {
    var output = [];
    var xHttp = new XMLHttpRequest();
    xHttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var dawaData = JSON.parse(this.responseText);
            dawaData.forEach(function (data) {
                output.push({ Id: data.kode, Name: data.navn, CountryId: 53, CountryText: "Danmark", RegionId: data.regionskode, RegionText: data.region.navn });
    }"GET", "", true);
    await xHttp.send();
    return output;

async function loadMunicipalities() {
    var select = document.querySelector("municipality");
    var data = await Municipalities;
    data.forEach(function (municipality) {
        var option = document.createElement("option");
        option.value = municipality.Id;
        option.text = municipality.Name;
        option.selected = select.value == municipality.Id;

21 thoughts on “Asynchronous loading of select list options”

  1. 695162 119557This style is steller! You most certainly know how to maintain a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (nicely, almostHaHa!) Amazing job. I really loved what you had to say, and more than that, how you presented it. Too cool! 891200


Leave a Comment