Schws
Schws

Reputation: 91

How to fire jQuery function on click event but only after the page is loaded?

I have a button that requests information from another site. This call is quite large and takes a couple of seconds to receive the response. Once I receive the response I want to display a modal to the user with some info from the response.

So my question is, how do I show the modal on click of my button, but only once I receive the payload back with the info needed to construct the message? Please take note that the web service call is not done in JavaScript. I am storing my message to the user in a hidden element on the page for the JS to pick up.

Here is what I have tried and hopefully explains what I am trying to accomplish.

$("#get_cost").click(function() {
    var myMessage = $("#responseEle").val();
    swal("Success!", myMessage, "success");
}).ready();

Btw... swal is just https://sweetalert.js.org/ which is really cool but not related to my question.

Upvotes: 1

Views: 58

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21628

You can poll every second for the condition you are looking for with a timeout. Run checkDone function on the button click.

let done = false;

function checkDone() {
  if (done) {
    console.log('Done');
  } else {
    console.log('Polling');
    setTimeout(checkDone, 1000); // Run checkDone again in 1,000 milliseconds
  }
}

checkDone();

setTimeout(() => { done = true; }, 5000);

Upvotes: 1

Related Questions