Monday, 8 April 2019

JavaScript value plugged in with PHP returns error

I created a quiz timer which uses a combo of javascript and PHP. PHP get the quiz's end time from a URL parameter called takingTest and plugs it in the javaScript code. However, it does not work for everyone. It works for everyone if I plug in the value manually. Any ideas what the problem is?

The URL parameter

enter image description here

I echoed the URL parameter using <?php echo $_GET['takingTest']; ?> and it showed the correct end time.

Echoed value with PHP

enter image description here

When it breaks, it returns a minus value and submits the quiz.

Minus value example

-10h -27m -225

My code looks like below:

<?php 

if(($_GET["started"]) === "true") {


?>  
<!--/*<!-- Quiz countdown block -->

    <script type="text/javascript" defer>

        $(function () {

// Set the date we're counting down to
var countDownDate = new Date("<?php echo $_GET['takingTest']; ?>").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="demo"
  document.getElementById("timer").innerHTML = hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
     $("#grader").trigger("click");
  }
}, 1000);

 });            


</script>

<?php } ?>



from JavaScript value plugged in with PHP returns error

No comments:

Post a Comment