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

152
Visualizações
How do I fetch data from a public API on form submit using vanilla JS

I am building a simple webpage where the user can enter a year in a text field and be presented with a list of F1 races for that year.

I am getting my data from this public API: http://ergast.com/mrd/ I need to achieve this in vanilla JS. I do not want to use jQuery.

So far I have tried the fetch method and I can console log:

fetch('http://ergast.com/api/f1/2020.json')
  .then(response => response.json())
  .then(data => console.log(data));

This shows me all the races for the year 2020.

However I need the user to input the year, which then gets queried with the API and then the results should be displayed.

The HTML looks like this:

<form>
   <label>
      <span>Full name</span>
       <input type="text" id="test" placeholder="">
    </label>
    <button type="submit" id="form-submit">
       Button
    </button>
</form>

There are many similar questions already on SO but none that have been helpful for me.

EDIT

I also need to try and access the race results for any given year, Race results are nested within the array > data.MRData.RaceTable.Races.0.Results and I'm not sure how to access these values.

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

0

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  <style>
     fieldset {
       margin: 10px;
     }
  </style>
  </head>
  <body>
    <form>
      <label>
        <span>Year</span>
        <input value="2020" type="text" id="year" placeholder="type a year" />
      </label>
      <button type="submit" id="form-submit">
        Button
      </button>
    </form>
    <div id="result"></div>

    <script>
      const result = document.getElementById("result");
      document.querySelector("form").addEventListener("submit", (e) => {
        e.preventDefault();
        const year = document.getElementById("year").value;
        fetch("http://ergast.com/api/f1/" + year + ".json")
          .then((response) => response.json())
          .then((data) => {
            result.innerHTML = `<b>results for ${year}</b>`;
            data.MRData.RaceTable.Races.forEach((race) => {
              result.innerHTML += `
<fieldset>
  <h4> ${race.raceName} </h4>
  <a target="_blank" href="${race.Circuit.url}"> ${race.Circuit.circuitName} </a>
  <p> ${race.date} - ${race.Circuit.Location.country} </p>
</fieldset>`
            });
          });
      });
    </script>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is one approach. You will need to think about how you want to display the data though. Many paragraphs isn't very user friendly.

let body = document.querySelector('body');

document.querySelector("form").addEventListener('submit', (e) => {
  const year = document.getElementById('year').value;
  e.preventDefault();
  fetch(`https://ergast.com/api/f1/${year}.json`)
    .then(response => response.json())
    .then(data => {
      (data.MRData.RaceTable.Races).forEach(races => {
        for(race in races) {
          let para = document.createElement('p');
          para.innerText = races[race];
          body.appendChild(para);
        }
      })
    })
  })
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form>
    <label>
       <span>Year</span>
        <input type="text" id="year" placeholder="">
     </label>
     <button type="submit" id="form-submit">
        Button
     </button>
  </form>
  <script src="./script.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

The API URL is just a string, therefore the easiest way would be adding a button to your form and put the API call in onclick() event attribute of button.

<form>
   <label>
      <span>Full name</span>
       <input type="text" id="test">
    </label>
    <button id="form-submit" onclick="apiFetcher()">
       Fetch!
    </button>
</form>
<p id="result"></>

And the JS function:

function apiFetcher()
{
    var year = document.getElementById("test").value;
 
   fetch("http://ergast.com/api/f1/" + year + ".json")
  .then(response => response.json())
  .then(data => document.getElementById("result").innerText = data);
}

Note that there are about or more than 10 ways to get an input element's value but as for calling the API you have to concatenate the user inputted year to rest of the URL no matter how you get the value.
By not using <button type="submit"> but a simple <button> you remove the need to handle default event.

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