i have a code that count up the time spent on the page it strat count up since it clicked now my problem is how to record the time when click on submit button and send it to the database

< script >
  var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);

function setTime() {
  secondsLabel.innerHTML = pad(totalSeconds % 60);
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
<div id="navbar" class="collapse navbar-collapse">
 <ul class="nav navbar-nav">
<label id="minutes">00</label>:<label id="seconds">00</label><label id="houres">:00</label><li>
<input type="submit" name="register" class="btn btn-info" value="Submit" />

1 Answers

Leonard Pauli On

Try breaking down the question. Start of by analysing your program flow:

Currently, every second (1000 ms):

  • the setTime function is called (update)
  • which increments a variable totalSeconds ((data) model / state)
  • transforms it into minutes and seconds
  • formats the values into padded strings using pad (view model)
  • updates the view (Document Object Model, DOM, HTML) with the new values (render the view)

Now, you want to send some data to the database... lets break it down:

  • starting in the client (eg. a webpage)
  • user clicks on submit button (interaction in view triggers action/event)
  • (before this, a handler/listener for that event should have been registered)
  • the handler function that was registered as a listener for the event is invoked
  • in the handler, the data is formatted (in a way the server likes it, eg. as JSON, or plain text in the query part of the url)
  • the data is sent to the server (eg. as an http request using AJAX through XMLHTTPRequest through the new fetch api)
  • the server receives the request, and passes it to a "handler"
  • in PHP, this is can be done using ".htaccess" (optional) to route the request to a PHP file, in which some variables containing information about the request are provided/pre-set see https://www.php.net/manual/en/reserved.variables.php for json decode, see: PHP decode JSON POST for simple query variables, see https://www.php.net/manual/en/reserved.variables.get.php
  • the "handler" can then process the request data (eg. validate it and save it in a database), and return a response
  • the client then receives the response and can ignore or act on it, eg. by showing an error/success message

The above-mentioned flow is quite common in the world of web development, more generally:

  • initial state is loaded
  • when state is loaded or updated:
    • the view model is updated (based on the state)
    • the view is rendered (based on the view model)
  • when an event is triggered (eg. user interaction, or a timer):
    • a handler is invoked, that
      • updates the state (and thus the view)
      • and, optionally, sends some data to the server

Following this pattern, the code could be rewritten:

<span class="time">
  <span class="mm"></span>:<span class="ss"></span>
<button class="submit-time">Save time</button>


const view = {
  mm: document.querySelector('.time .mm'),
  ss: document.querySelector('.time .ss'),
  submit: document.querySelector('.submit-time'),

const render = ()=> {
  const viewModel = viewModelFromState(state)
  view.mm.innerText = viewModel.mm
  view.ss.innerText = viewModel.ss

const viewModelFromState = state=> ({
  mm: pad(Math.floor(state.secondsTotal / 60)),
  ss: pad(state.secondsTotal % 60),

const state = {
  secondsTotal: 0,

const update = ()=> {
  state.secondsTotal += 1

const eventListeners = {
  submit: ()=> {
    alert('value is '+state.secondsTotal)

    const onSuccess = (text)=> {
      alert("Saved! "+text)

    const onFail = (error)=> {
      alert("Couldn't save!\n" + error)

      .then(res=> res.text()).then(onSuccess)
      .catch(err=> onFail(err))

const setupEventListeners = ()=> {
  view.submit.addEventListener('click', eventListeners.submit)

// api

const saveSecondsTotal = (secondsTotal)=> {
  const val = ''+secondsTotal // explicitly convert number to string (unnecessary)
  const url = '/save-seconds-total'
  const queryString = 'val='+val
  const fullUrl = url+'?'+queryString
  return fetch(fullUrl)

// helpers

const pad = (val)=> {
  const str = ''+val
  return str.length < 2? '0' + str: str

// start

setInterval(()=> {
}, 1000)


I "simplified" the example by removing unused (eg. hour and some markup). I'm also using some language features like arrow functions, objects, const, ternary operator, promises, etc, that might be nice to look up.

Though, for this example, a "simpler" and explicit solution could be:

  <span id="mm"></span>:<span id="ss"></span>
<button onclick="submitTime">Save time</button>


// state + render

var mmElement = document.getElementById('mm')
var ssElement = document.getElementById('ss')

var secondsTotal = 0

function update () {
  secondsTotal += 1

  var mm = pad(Math.floor(secondsTotal / 60))
  var ss = pad(secondsTotal % 60)

  mmElement.innerText = mm
  ssElement.innerText = ss

// submit

function onSubmitSuccess (text) {
  alert("Saved! "+text)

function onSubmitFail (error) {
  alert("Couldn't save!\n" + error)

function saveSecondsTotal (secondsTotal) {
  return fetch('/save-seconds-total?val='+secondsTotal)
    .then(function (response) {return response.text()})

function submitTime () {
  alert('value is '+secondsTotal)

// helpers

function pad (val) {
  var str = ''+val
  if (str.length < 2) {
    return '0' + str
  return str

// start

setInterval(update, 1000)


The interesting part here, to answer your question, is the "submit" section. The PHP side would look something like:

<?php // in http-root/save-seconds-total.php

$val = $_GET["val"];
$secondsTotal = intval($val);

// ... database specific code ...

echo "Saved ".$secondsTotal." seconds!"


I would recommend you to read up and work through more examples/tutorials. When asking questions here, please show what you've tried, and possibly some hypotheses. Try to strip away all unnecessary details to get to the core of the question. Hopefully you're asking because your interested in understanding, and not because you want some homework done for you...