i'm new to API's and am building a webpage that calls an API and gets some data to build a table and display it. Currently the page runs the buildTable() function on page load and takes a URL value. Here is the entire page code:
function buildTable(url) {
fetch(url)
.then(response => response.json())
.then(serverList => {
let table = document.querySelector('#mainTable');
table.innerHTML = '';
table.innerHTML = '<tr><th>Server Name</th><th>Rank</th><th>Players</th><th>Last Wipe</th><th>Country</th></tr>';
for (let item in serverList.data) {
console.log(serverList.data[item]);
let row = document.createElement('tr');
let serverName = document.createElement('td');
serverName.innerHTML = `${serverList.data[item].attributes.name}`;
let serverRank = document.createElement('td');
serverRank.innerHTML = `${serverList.data[item].attributes.rank}`;
let serverPlayers = document.createElement('td');
serverPlayers.innerHTML = `${serverList.data[item].attributes.players}/${serverList.data[item].attributes.maxPlayers}`;
let serverWipe = document.createElement('td');
let currentTime = new Date();
let wipeTimeString = `${serverList.data[item].attributes.details.rust_last_wipe}`;
let wipeTime = new Date(wipeTimeString);
let daysWiped = (currentTime.getDate() - wipeTime.getDate());
let wipeMessage = `${daysWiped} Days ago`;
serverWipe.innerHTML = `${wipeMessage}`;
let serverCountry = document.createElement('td');
serverCountry.innerHTML = `${serverList.data[item].attributes.country}`;
row.appendChild(serverName);
row.appendChild(serverRank);
row.appendChild(serverPlayers);
row.appendChild(serverWipe);
row.appendChild(serverCountry);
table.appendChild(row);
}
})
}
buildTable(`https://api.battlemetrics.com/servers?page[size]=100&filter[game]=rust`);
To filter/sort data from the API I only need to change the existing URL by adding parameters on the end. Example:
`https://api.battlemetrics.com/servers?page[size]=100&filter[game]=rust&filter[search]=large`
My question is how do I take user input to change the URL and load the new data? I tried using a form with text inputs and call the buildTable() function with the new URL, but it just refreshes the page and the default buildTable() data displays. I also tried preventdefault() with the form but it didn't work.
preventDefault()on the submission event or the page will refresh. The main task here is to insert the input values into the URL, which is just a string. That is the code we need to see, not the pretty much irrelevant and working buildTable function.