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

59 lines
1.7 KiB
JavaScript

//Search stuff
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 = "";
for (const key of Object.keys(json.data[0]))
{
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 = "";
for (const row of json.data)
{
body += "<tr>";
for (const key of Object.keys(row))
{
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");
}
}));
});