Json data populate in select option where data in side another array

Viewed 52

I want to show JSON data to HTML select option but the problem is data is inside another array

HTML code

<select id="ExchCode" class="form-control" name="ExchCode"  autocomplete="off" required>
    <option id="exchange-house" value=""></option>
</select>

JSON Code result from Ajax request

 {
      "status": "200",
      "success": true,
      "mesg": "data found",
      "data": [
        {
          "exchangeCode": "0",
          "exchangeName": "-SELECT EXCHANGE HOUSE-"
        },
        {
          "exchangeCode": "24NME",
          "exchangeName": "PAYPAL"
        },
        {
          "exchangeCode": "AAM112",
          "exchangeName": "AL AHALIA "
        },
        
        {
          "exchangeCode": "ZEN042",
          "exchangeName": "ZENJ EXCHANGE CO. W.L.L,"
        }
      ]
    }

My jquery to populate the data from ajax request

   $(document).ready(function() {
        //Make an Ajax request to a PHP script called get-exchange-house.php
        $.ajax({
            url: 'fetch-data.php',
            type: 'get',
            dataType: "json",
            success: function(response){
                
                //console.log(response);
     
                $.each(response.data, function(data.exchangeCode, data.exchangeName){
                    //Use the Option()
                    var option = new Option(exchangeCode, exchangeName);
                    
                    $(option).html(exchangeName);
                    //Append the option to our Select element.
                    $("#ExchCode").append(option);
                });
     
                //Change the text of the default "exchange-house" option.
                $('#exchange-house').text('Select Exchange House');
     
            }
        });
});
2 Answers
  • Don't append inside loops. Append only once outside of a loop
  • Use Array.prototype.reduce() to reduce an array into a Document Fragment
  • Use new DocumentFragment() and append your Options inside it
  • Append your fragment to a destination Element
  • It's useful to create a reusable function that does what it says like i.e: populateExchange() that accepts the data Object response as argument
  • $.ajax default "type" is "GET" - so no need to re-override the default.

const populateExchange = (res) => {
  const options = res.data.reduce((DF, item, i) => {
    const opt = new Option(item.exchangeName, item.exchangeCode, false, !i);
    if (!i) opt.disabled = true;
    DF.append(opt);
    return DF
  }, new DocumentFragment());
  $("#ExchCode").append(options); // Append outside the loop
};

// DEMO ONLY:
populateExchange({
  "status": "200",
  "success": true,
  "mesg": "data found",
  "data": [
    {"exchangeCode": "0","exchangeName": "-SELECT EXCHANGE HOUSE-"},
    {"exchangeCode": "24NME","exchangeName": "PAYPAL"},
    {"exchangeCode": "AAM112","exchangeName": "AL AHALIA "},
    {"exchangeCode": "ZEN042","exchangeName": "ZENJ EXCHANGE CO. W.L.L,"},
  ]
});

// USE LIKE:
jQuery($ => { // DOM Ready and $ alias in scope
  $.ajax({
    url: 'fetch-data.php',
    success: populateExchange
  });
});
<select id="ExchCode" class="form-control" name="ExchCode" autocomplete="off" required></select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

The parameters in the callback for $.each are index, element. So you can call exchangeCode and exchangeName on the second parameter once you've updated that correctly.

$.each(response.data, function(index, element){
    //Use the Option()
    var option = new Option(element.exchangeCode, element.exchangeName);
                   
    $(option).html(element.exchangeName);
     //Append the option to our Select element.
     $("#ExchCode").append(option);
});
Related