Please tell me where I went wrong with this code.
Well, .php scripts are executed by the server, before result is sent to the user. Wrapping it in <script>
</script>
won't help. So, yours code flow looks like:
→ Serverside, php:
<?php
...
?>
<script>
function secondPassed() {
document.getElementById('time').value = parseInt(document.getElementById('time').value) + 1;
int val = 0;
num = "<?php
$insert = mysql_query('INSERT INTO tbl_timer VALUES(\'\', \"."$val".\" )',$connection);
// error notice (probably suppresed), there is no $val variable defined...
// If somethig _will_ be inserted, it will contain just (0) or ("")
?>";}
</script>
→ Client side, html:
...
<script>
function secondPassed() {
document.getElementById('time').value = parseInt(document.getElementById('time').value) + 1;
int val = 0;
num = "0";}
</script>
And when browser executes that <script>
, it will just store incremented value in #time
, and nothing else.
If you want pass something from javascripts to server, you must make request to the server, always. That's just logical.
So, as @adeneo suggested, you either must use:
ajax
request (aynchronous/synchronous).
- Cookies (synchronous, page reload will be required to pass cookies to server)
- Sockets (asynchronous/synchronous, and there is plenty of socket-related solutions)
iframe
s (asynchronous, can cause unwanted side effects).
- Don't use serverside database at all (if appropriate). Just use browser's
localStorage
or similar.