Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
Fetch value from server upon loading the window

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 class="count-area">
            <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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 onload="clicksLoad()">
  <h1>Just another counter</h1>
  <div class="count-area">
    <button type="button" onClick="increment()">+</button>
    <button type="button" onClick="decrement()">-</button>
    <p>Count: <a id="clicks"></a></p>
  </div>
</body>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!