document.getElementById('terrainForm').addEventListener('submit', function(event) { event.preventDefault(); var terrain = document.getElementById('terrainType').value; fetch('https://gammaworld.gmgauthier.com/roll/encounter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "terrain": terrain }) }).then(response => { if (!response.ok) { throw response } return response.json() // we only get here if there is no error }).then(json => { //Handle null encounter let encounterText = json.encounter ? json.encounter : "No Encounter"; let resultSection = document.getElementById('resultSection'); resultSection.innerHTML = ''; // Create an image element and set its src to the corresponding jpeg image let imgElement = document.createElement("img"); imgElement.alt = encounterText; imgElement.width = 500; // You can set width as per your choice imgElement.height = 500; // You can set height as per your choice imgElement.onerror = function() { this.onerror=null; this.src='./img/404.jpg'; } imgElement.src = "./img/" + encounterText + ".jpg"; // Append the image element to the resultSection resultSection.appendChild(imgElement); }).catch(err => { err.text().then(errorMessage => { let imgElement = document.createElement("img"); imgElement.src = "./img/404.jpg"; imgElement.width = 500; imgElement.height = 500; let resultSection = document.getElementById('resultSection'); resultSection.innerHTML = ''; resultSection.appendChild(imgElement); }) }); });