Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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:

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda