title: JS Countdown Timer from PHP variable (AJAX)
body: <p>The script below returns time since the last customer registered in minutes and seconds. The variable of registration date is pulled from the separate PHP file.</p>
  
  <p>How to combine the two to get a dynamic result (AJAX) as soon as new customer registers.</p>
  
  <p>The script below works well, but only updates on reload.</p>
  
  <p><strong>index.php</strong></p>
  
  <pre><code>&lt;?php
      require_once('get_file.php')
  ?&gt;
  
  &lt;script src="https://code.jquery.com/jquery-1.11.0.min.js"&gt;&lt;/script&gt;
  
  &lt;script type="text/javascript"&gt;
  var currenttime = &lt;?php print json_encode($todaysDate, JSON_UNESCAPED_SLASHES) ?&gt;;
  var lastsale = &lt;?php print json_encode($orderCreated, JSON_UNESCAPED_SLASHES) ?&gt;;
  
  var montharray=new Array("01","02","03","04","05","06","07","08","09","10","11","12")
  var serverdate=new Date(currenttime)
  var lastordercreated=new Date(lastsale)
  
  function padlength(what){
      var output=(what.toString().length==1)? "0"+what : what
      return output
  }
  
  function displaytime(){
      serverdate.setSeconds(serverdate.getSeconds()+1)
  
      // Todays Date
      var datestring=padlength(serverdate.getDate())+"/"+montharray[serverdate.getMonth()]+"/"+serverdate.getFullYear()
  
      // Current Time
      var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
  
      // Last Ordered Count
      var lastorderedcount=padlength(serverdate.getTime()) - padlength(lastordercreated.getTime())
  
      var minutes = Math.floor((lastorderedcount % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((lastorderedcount % (1000 * 60)) / 1000);
      var lastordercountdown = minutes+":"+seconds
  
      // Output
      document.getElementById("todaysdate").innerHTML=datestring
      document.getElementById("currenttime").innerHTML=timestring
      document.getElementById("lastordered").innerHTML=lastordercountdown
  
  }   
  
  function updateAjax() {
      $.ajax({
          url: 'getLastData.php',
          success: function(res) {
              currenttime         = res.currentDate;
              lastsale            = res.orderCreated;
              serverdate          = new Date(currenttime);
              lastordercreated    = new Date(lastsale);
              console.log(res);
          }
      });
  }
  
  window.onload=function(){
  setInterval('displaytime()', 1000)
  setInterval(updateAjax, 1000)
  }
  &lt;/script&gt;
  
  &lt;span id="lastordercountdown"&gt;&lt;/span&gt;
  </code></pre>
  
  <p><strong>getLastData.php</strong></p>
  
  <pre><code>&lt;?php
      require_once('get_data.php');
  
      print json_encode([
          'currentDate' =&gt; $todaysDate,
          'orderCreated' =&gt; $orderCreated
      ],JSON_UNESCAPED_SLASHES);
  ?&gt;
  </code></pre>