gammatools/web/assets/js/encounter.js

48 lines
1.7 KiB
JavaScript

import {loadingGif, setResultImage} from "./loading.js";
import {setCreatureTable} from "./setCreatureTable.js";
import {androidResultTable} from "./androidResultTable.js";
document.getElementById('terrainForm').addEventListener('submit', function (event) {
event.preventDefault();
const terrain = document.getElementById('terrainType').value;
const queryParams = new URLSearchParams({
terrain: terrain,
});
// Insert the loading.gif before making the fetch request
let resultSection = document.getElementById('resultSection');
let imgElement = loadingGif(resultSection);
setTimeout(() => {
fetch(`${window.BASE_URL}/gameplay/encounter?${queryParams}`)
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json(); // we only get here if there is no error
})
.then((json) => {
resultSection.innerHTML = ''; // Clear previous content
if (Object.keys(json).length === 1) { // Short version of response
let name = json.name !== null ? json.name : 'No Encounter';
setResultImage(name);
} else { // Long version of the response
if (json.name === 'android') {
androidResultTable(json, json.name);
} else {
setCreatureTable(json, json.name);
}
}
})
.catch((err) => {
err.text().then(() => {
imgElement.src = '/assets/img/404.jpg';
});
});
}, 1000);
});