Skip to content

Instantly share code, notes, and snippets.

@Yengas
Last active November 14, 2015 09:56
Show Gist options
  • Select an option

  • Save Yengas/a239598f3da8cd4b2d72 to your computer and use it in GitHub Desktop.

Select an option

Save Yengas/a239598f3da8cd4b2d72 to your computer and use it in GitHub Desktop.
Populating a dropdown list with an ajax request.
function DropdownLoader(options) {
var options = options,
loading = false,
completed = false;
var obj = document.querySelector(options.selector);
function load() {
loading = true;
var xml = new XMLHttpRequest();
xml.open("GET", options.url, true);
options.loading();
xml.onload = function() {
// Loading işleminin bittiğini söylüyoruz.
loading = false;
// Ajax cevabını parseleyip, sonuç var ise dropdown'a ekle
result = options.parser(this.responseText);
if (result != false) {
completed = true;
obj.innerHTML = result;
} else {
completed = !!!options.retry;
if (options.retry) load();
}
options.finished(result != false ? null : -1);
};
// Veri yüklemede hata olursa çalışacak olan fonksiyonu belirtiyoruz.
xml.onerror = function() {
loading = false;
options.finished(this);
};
xml.send();
}
obj.addEventListener("click", function() {
if (loading || completed) return false;
load();
});
}
<select id="combobox">
<option disabled selected></option>
<option>Loading...</option>
</select>
new DropdownLoader({
selector: "#combobox",
url: "http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&cluster=yes&appid=2de143494c0b295cca9337e1e96b00e0",
parser: function(response) {
var weather_data = JSON.parse(response),
result = "";
for (var key in weather_data["list"]) {
var data = weather_data["list"][key];
result += "<option>" + data["name"] + '-' + data["weather"]["0"]["main"] + "</option>"
}
return result;
},
loading: function() {
console.log("Loading...");
if (this.times == undefined) this.times = 0;
if (++this.times == 5) {
this.retry = false;
console.log("No more retries...");
}
},
finished: function(err) {
console.log("Finished: ", err);
},
retry: true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment