Home > Back-end >  how do I sort response fetched from AJAX request and map them as <option> to <select> ta
how do I sort response fetched from AJAX request and map them as <option> to <select> ta

Time:12-14

I am trying to sort the response fetched from backend, using AJAX. This is my code:

let $select = $("#colony_code");
  
$.ajax({
      url: 'backend.php',
      type: 'POST',
      data: { "input": "fetch_colony_codes" }, 
      dataType: 'json', 
      success: function(response) {
        let selectedValue = $select.val();
        let html = response.filter((e, i, a) => a.indexOf(e) === i).map(item => `<option value="${item}">${item}</option>`);
        $select.html(html).val(selectedValue);
      },
      complete: function() {}
});

Now, I want all the options to be sorted in my <select> tag. How do I sort the options?

CodePudding user response:

Man, I am stupid. Just adding response.sort(); in the beginning of the success(..) solved my problem. XD

  • Related