简体   繁体   中英

Javascript Countdown Timer Repeat and execute php code

i have javascript countdown timer from 30 -> 0.

var count = 30;

var counter = setInterval(timer, 1000);

function timer() {
  count = count - 1;
  if (count <= 0) {
    clearInterval(counter);
    return;
  }

  document.getElementById("timer").innerHTML = count;
}

and html:

<span id="timer">30</span>

I want the countdown to repeat automatically when it is over (after 30 secs) and execute php code (Select and show data from mysql)

At the end of your countdown.. Check for if (count <= 0) -- If it does, run your AJAX call to a file -- say --- file.php which contains your php and sql . Also in the if you are going to reset your counter back to 30.

<html>
<head>

</head>
<body>
<span id="timer">30</span>
<div id="#ajax-results"></div>

<script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>

<script>
    var count=30;

    var counter=setInterval(timer, 1000);

    function timer()
    {
        count=count-1;
        if (count <= 0)
        {
            count=30;
            $.ajax({
                url: 'file.php',
                type: 'POST',
                data: 'somevariable=whatever',
                success: function(data) {
                    //called when successful
                    $('#ajax-results').html(data);
                }
            });
        }

        document.getElementById("timer").innerHTML=count;

    }
</script>
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM