简体   繁体   中英

when Countdown timer = 0, alert button or submit form

When my timer count to 00:00:00 alert('Get Result') button or submit the form

I cant even alert message in response.php.

This is Where I select the duration from database

while($row=mysqli_fetch_array($res))
{
    $duration=$row["duration"];
}

$_SESSION["duration"]=$duration;
$_SESSION["start_time"]=date("Y-m-d H:i:s");

$end_time=$end_time=date('Y-m-d H:i:s', strtotime('+'.$_SESSION["duration"].'minutes',strtotime($_SESSION["start_time"])));

$_SESSION["end_time"]=$end_time;

This is response.php

<?php
session_start();

$from_time1=date('Y-m-d H:i:s');
$to_time1=$_SESSION["end_time"];
$timefirst=strtotime($from_time1);
$timesecond=strtotime($to_time1);

$differenceinseconds=$timesecond-$timefirst;
if($differenceinseconds<0){
    // This is for when timer smaller then 0 then = 00:00:00
    $differenceinseconds=0;
    echo "TIME UP<br>";
//I try to alert a simple message here, and dint work. Why is this happen
}
echo gmdate("H:i:s",$differenceinseconds);

?>

Here is the javascript in quiz page

<script type="text/javascript">
    var x =setInterval(test,1000);

    function test()
    {
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","response.php",false);
        xmlhttp.send(null);
        document.getElementById("response").innerHTML=xmlhttp.responseText;
    }
</script>

The display timer tag

<div id=response class=timer style=font-size:30px></div>

The Form name and the button

<form name=myfm method=post action=quizz.php>
    <input type=submit name=submit value='Get Result'>

Your PHP should only get the difference in time. That means that PHP will always output a format of HH:mm:ss , and no other text or values, which you then get in JavaScript. Ensuring that the output is always the same, unless you're using encoded arrays, means that you can design your code to expect the values you always send.

$differenceinseconds = $timesecond - $timefirst;
if ($differenceinseconds < 0){
    $differenceinseconds = 0;
}
echo gmdate("H:i:s", $differenceinseconds);

You can then check that value after you fetch the values in JavaScript, since you now know that the only thing printed by your response.php is a time in the format of HH:mm:sss .

function test() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "response.php", false);
    xmlhttp.send(null);
    var response = xmlhttp.responseText;

    document.getElementById("response").innerHTML = response;
    if (response == "00:00:00") {
        alert("Time's up!");
    }
}

If you want to submit the form as well, add a submit() within the condition if (response == "00:00:00") { .

document.getElementsByName('myfm')[0].submit();

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