Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic API requests from user input

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

`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.

>Solution :

My question is how do I take user input to change the URL and load the new data?

If you use an URL object, you can conveniently set the individual query parameters.

Here is an example assuming an input box #filterInput:

const filterInput = document.querySelector('#filterInput')

const url = new URL('https://api.battlemetrics.com/servers?page[size]=100&filter[game]=rust')
url.searchParams.set('filter[search]', filterInput.value)

buildTable(url)

I tried using a form with text inputs […] but it just refreshes the page

If you do use a form for the user input, you have to call preventDefault in the submission event as well. Note that it’s with capital D (unlike what you wrote in your question) and you need to call it on the event object that gets passed as first argument into your event listener:

document.querySelector('#myForm').addEventListener('submit', e => {
  e.preventDefault()
  
  // code from above here
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading