0

I have an API which is return about over 10.000 records it's implemented to return in pagination, each time it return 25 records.

Now, I want to populate all records to select input on HTML page, currently I call ajax to API and parse JSON object to append options. But because the API is returning in pages, I don't know how to query all the records to display all item to user, for now I can only display 25 items.

My idea is to catch the event when user scroll to the end of the list and then fire a API call again for next page, continue populate data to the dropdown dynamically until it reach the last page. But I don't know how to do that, can you guys help me?

This is my code.

HTML

<div class="col-md-6 target-geo-holder">
  <select class="form-control target-geo">
  </select>
</div>

JS

var url = "API Link";
var list = [];
$.get(url, function (data) {
     if (data.success) {
         list = data.records;
     } else {
         console.log("No data available");
     }
});
var targetGeo = fragment.find(".target-geo");
targetGeo.empty();

targetGeo.append($("<option />").attr("value", "matchAll").text("None"));

list.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});
for (var i = 0; i < list.length; i++) {
     var item = list[i];
     var option = $("<option>").attr("value", item.id).text(item.name);
     targetGeo.append(option);
}
Thong Vo
  • 809
  • 1
  • 9
  • 21
  • 4
    You need to create a custom drop-down box to achieve the above requirement or plugins. – Aravind Sivam Apr 04 '17 at 08:04
  • 2
    You won't manage this with a standard ` – freedomn-m Apr 04 '17 at 08:07
  • In your provided code, put all the code after the `.get.` `})` inside the `if (data.success)` block. See here for more info: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323 – freedomn-m Apr 04 '17 at 08:09
  • @freedomn-m Can you tell me why should I do that? – Thong Vo Apr 04 '17 at 10:00
  • Because, simply, if you open a drop down with *10,000* items in it, finding the one you want will be an extremely horrible experience (user experience, UX). Having to scroll down page after page after page to find the one you want... ugh. It's a great example of how to annoy your users. – freedomn-m Apr 04 '17 at 10:04
  • Or did you mean why to move the code? :) Your `$.get` runs **asynchronously**, so `list` will still be empty when the `list.sort` etc code runs as `list = data.records;` is the *last* code to run. – freedomn-m Apr 04 '17 at 10:05

0 Answers0