3

Good morning, I have a fetch async function in my js file for call ajax members into a goverment table. I want to add a spinner while the data is been loading and also I want to hide the table titles and the dropdown menu as well as checkboxes while the spinner (ajax) is working. I´m not using any framework, just js vanilla. I´m a student and I can´t use jquery for this. I have the spinner but it doesn´t disapear when the data appears on the table. Thank you so much!

async function getData(chamber) {
  members = await fetch(`https://api.propublica.org/congress/v1/113/${chamber}/members.json`, {
      method: "GET",
      headers: new Headers({
        'X-API-Key': 'iv8LMc9T9sQKOc0EfDC1NLtQU68pFsF6O6W3NPJz'
      })
    })

    .then(response => response.json())
    .then(data => data.results[0].members)
    .catch(err => console.log(err))
  webLogic(chamber);
  document.getElementsById("loader").style.display = "none"
}
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Nikita99
  • 45
  • 1
  • 6

1 Answers1

5

You can achieve this by setting innerHTML of your element - note that the setTimeout is just used to "mock" your async request here. Of course you'd need something like

.then((resolvedData) => document.getElementById('myDiv').innerHTML = resolvedData)

here the snippet:

document.getElementById('load').addEventListener('click', function () {
  document.getElementById('content').innerHTML = '...'
  setTimeout(function () {
    document.getElementById('content').innerHTML = 'content loaded!'
  }, 2000)
})
<div id="content"></div>
<button id="load">load</button>
messerbill
  • 5,499
  • 1
  • 27
  • 38
  • Sorry, I don´t understand. – Nikita99 Feb 07 '20 at 14:11
  • The first line of code works but it shows the title of the table and then disapear – Nikita99 Feb 07 '20 at 14:12
  • what do you not understand? The relevant part is `document.getElementById('content').innerHTML = 'content loaded!'` which has to be executed once the request was resolved. - and of course the `innerHTML` should be the spinner **before** the promise was resolved – messerbill Feb 07 '20 at 14:20