I am trying to pull the contents of the ASV bible off the api at biblia.api and populate my select dropdown with the data, however I am doing something wrong as the data is not populating my select dropdown. However, I know the endpoint is correct and it does load up the json object with the bible contents in my console.
$(document).ready(function(){
let dropdown = document.getElementById('books');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Book of the Bible';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'https://api.biblia.com/v1/bible/contents/ASV?key=aa43781d7b806b8d6764191dce895e10';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const books = JSON.parse(request.responseText);
let option;
for (let i = 0; i < books.length; i++) {
option = document.createElement('option');
option.text = books[i].passage;
option.value = books[i].passage;
dropdown.add(option);
console.log(books[i].passage);
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
Consider the following.
$(function() {
function loadSelect(target, url) {
var dropdown = $(target);
var defaultOption = $('<option>').html("Choose Book of the Bible").appendTo(dropdown);
$.getJSON(url, function(results) {
$.each(results.books, function(i, book) {
$("<option>", {
value: i
}).html(book.passage).appendTo(dropdown);
});
});
}
loadSelect("#books", "https://api.biblia.com/v1/bible/contents/ASV?key=aa43781d7b806b8d6764191dce895e10");
});
It is considered a better practice to use all JavaScript or jQuery and not to mix them. You might like to use $.getJSON()
.
Your problem is that you are iterating over "responseText", which contains only one item named books.
To do what you try to achieve, you should use something like that in your request.onload
function :
const data = JSON.parse(request.responseText);
const books = data.books;