Javascript Web Page using an API
<table>
<thead>
<tr>
<th>Song</th>
<th>Banger</th>
<th>Not Banger</th>
</tr>
</thead>
<tbody id="result">
</tbody>
</table>
const resultContainer = document.getElementById("result");
const BANGER = "banger";
const NOT = "not banger";
const url = "https://flask.maniflpt.com/api/jokes";
const like_url = url + "/like/";
const jeer_url = url + "/jeer/";
const options = {
method: 'GET',
mode: 'cors',
cache: 'default',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
};
const put_options = {...options, method: 'PUT'};
fetch(url, options)
.then(response => {
if (response.status !== 200) {
error('GET API response failure: ' + response.status);
return;
}
response.json().then(data => {
console.log(data);
for (const row of data) {
const tr = document.createElement("tr");
const song = document.createElement("td");
song.innerHTML = row.id + ". " + row.song;
const banger = document.createElement("td");
const banger = document.createElement('button');
banger_but.id = BANGER+row.id
banger_but.innerHTML = row.banger;
banger_but.onclick = function () {
reaction(BANGER, like_url+row.id, banger_but.id);
};
banger.appendChild(banger_but);
const not = document.createElement("td");
const not_but = document.createElement('button');
not_but.id = NOT+row.id
not_but.innerHTML = row.not;
not_but.onclick = function () {
reaction(NOT, jeer_url+row.id, not_but.id);
};
boohoo.appendChild(not_but);
tr.appendChild(song);
tr.appendChild(banger);
tr.appendChild(not);
resultContainer.appendChild(tr);
}
})
})
.catch(err => {
error(err + " " + url);
});
function reaction(type, put_url, elemID) {
fetch(put_url, put_options)
.then(response => {
if (response.status !== 200) {
error("PUT API response failure: " + response.status)
return;
}
response.json().then(data => {
console.log(data);
if (type === BANGER)
document.getElementById(elemID).innerHTML = data.banger;
else if (type === NOT)
document.getElementById(elemID).innerHTML = data.not;
else
error("unknown type: " + type);
})
})
.catch(err => {
error(err + " " + put_url);
});
}
function error(err) {
console.error(err);
const tr = document.createElement("tr");
const td = document.createElement("td");
td.innerHTML = err;
tr.appendChild(td);
resultContainer.appendChild(tr);
}