Home > Back-end >  Fetch value from server upon loading the window
Fetch value from server upon loading the window

Time:05-11

I want it to load as soon as I open the window after fetching the data from the server side.

Here's the HTML:

    <body>
        <h1> Just another counter </h1>
        <div >
            <button type="button" onClick="increment()">   </button>
            <button type="button" onClick="decrement()"> - </button>
            <p>Count: <a id="clicks">0</a></p>
        </div>
    </body>
</html>

Here's the client side javascript:

window.onload = function() {
  fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};

function increment() {
  fetch("/increment").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);

};

function decrement() {
  fetch("/decrement").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
  };

Once the increment decrement buttons are pressed then the correct count shows up, but until then it remains 0.

CodePudding user response:

Instead of using windows.onload try using onload="myFunction()" on body :

function clicksLoad() {
  fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};

function increment() {
  fetch("/increment").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);

};

function decrement() {
  fetch("/decrement").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
  };
<body onl oad="clicksLoad()">
  <h1>Just another counter</h1>
  <div >
    <button type="button" onClick="increment()"> </button>
    <button type="button" onClick="decrement()">-</button>
    <p>Count: <a id="clicks"></a></p>
  </div>
</body>

CodePudding user response:

Try to listen to the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', function() {
   fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
});
  • Related