Assignment5 Js

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

const apiEndpoint =

"https://csunix.mohawkcollege.ca/~adams/10259/a6_responder.php";
const firstElem = document.querySelector("#first");
const contentDiv = document.querySelector("#content");
const tableDiv = document.querySelector("#content2");
const fetchBtn = document.querySelector("#b1");
const updateBtn = document.querySelector("#b2");
const submitBtn = document.querySelector("#b3");

fetchBtn.addEventListener("click", fetchDataAndDisplay);
updateBtn.addEventListener("click", () => handleButtonClick("update"));
submitBtn.addEventListener("click", () => handleButtonClick("submit"));

function updateFirstElement() {
firstElem.innerHTML = `<h1> Gaurav Patel,000898120</h1>`;
}

async function fetchDataAndDisplay() {


const response = await fetch(apiEndpoint, { credentials: 'include' });
const text = await response.text();
updateFirstElement(text);
}

async function handleButtonClick(type) {


const selectedOption = type === "update" ? getSelectedOption() : null;
const fetchUrl = type === "update" ? `${apiEndpoint}?choice=${selectedOption}` :
apiEndpoint;

try {
const response = await fetch(fetchUrl);

// Check if the response is valid JSON


const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
const data = await response.json();

if (type === "update") {


updateContentDiv(data);
} else {
updateTableDiv(data);
}
} else {
console.error("Invalid JSON response:", response);
}
} catch (error) {
console.error("Error fetching or processing data:", error);
}
}

function updateContentDiv(data) {
contentDiv.innerHTML = "";
data.forEach(item => {
const container = createContainer(item.name, item.url, item.series);
contentDiv.appendChild(container);
});
}

function createContainer(name, url, series) {


const container = document.createElement("div");
container.innerHTML = `<h2>${name}</h2><img src="${url}" style="width:
300px;"><p>${series}</p>`;
return container;
}

function updateTableDiv(data) {
tableDiv.innerHTML = "";
const createTable = document.createElement("table");
data.forEach(item => {
const rowData = [item.series, item.url, item.name];
createTable.appendChild(createRow(rowData));
});
tableDiv.appendChild(createTable);
}

function createRow(rowData) {
const row = document.createElement("tr");
rowData.forEach(content => row.innerHTML += `<td>${content}</td>`);
return row;
}

function getSelectedOption() {
const selectedInput = document.querySelector("input[name='choice']:checked");
return selectedInput ? selectedInput.value : null;
}

You might also like