DIDS-Coursework/DIS-COMP4039-CW2-psxrp11-20450011/psxrp11-20450011_InstallationFiles/js/search.js

66 lines
2.0 KiB
JavaScript

// document.addEventListener("DOMContentLoaded", () =>
// {
// fetch("isLoggedIn.php").then(res => res.json().then(json =>
// {
// if (json.message !== "ok")
// {
// window.location.href = "index.html";
// }
// }));
// });
document.querySelector("#searchType").addEventListener("change", e =>
{
if (e.target.value === "pn")
{
document.querySelector("#searchField").placeholder = "Find vehicle";
}
else
{
document.querySelector("#searchField").placeholder = "Find owner";
}
});
document.querySelector("#searchForm").addEventListener("submit", e =>
{
e.preventDefault();
let formData = new FormData();
formData.append("searchType", document.querySelector("#searchType").value);
formData.append("searchField", document.querySelector("#searchField").value);
fetch("search.php", {
method: "POST",
body: formData
}).then(res => res.json().then(json =>
{
if (json.message === "ok")
{
document.querySelector("#searchResults thead tr").innerHTML = "";
document.querySelector("#searchResults tbody").innerHTML = "";
console.log(Object.keys(json.data[0]));
Object.keys(json.data[0]).forEach(key =>
{
let header = key.substring(key.indexOf("_") + 1)
header = header.charAt(0).toUpperCase() + header.slice(1);
document.querySelector("#searchResults thead tr").innerHTML += `<th>${header}</th>`;
});
let body = "";
json.data.forEach(row =>
{
body += "<tr>";
Object.keys(row).forEach(key =>
{
body += `<td>${(row[key] === "null" || row[key] === null) ? "N/A" : row[key]}</td>`;
});
body += "</tr>";
});
document.querySelector("#searchResults tbody").innerHTML = body;
}
else
{
alert("No search results found");
}
}));
});