Link to home
Start Free TrialLog in
Avatar of Erikal
Erikal

asked on

how to auto submit hidden field onunload

I need a hidden field value (variable) to be automatically submitted when the user navigates away from the page or refreshes the page, without the use of any submit button.
The idea is to capture this value and use it in php.
Can anybody help.

I have raised several questions on this without any success so far.

Avatar of nanharbison
nanharbison
Flag of United States of America image

You need to give us more information. Is this in a form? Are you talking about the user being on a form, and then they go away without hitting the submit button and you want them to be able to come back and finish the form? Are they going to another page for a specific reason?

This might not be what you need, but how about setting a variable as soon as the user gets to this page?
Avatar of Erikal
Erikal

ASKER

Thanks for coming back to me on this nanharbison:
OK, let me try to explain if I can.
The page is for a test and these is a time limit on the page, 15 minutes.
This 15 minutes is set in a db field in miliseconds (900000) and retrieved by a javascript to start the countdown timer. If the user completes the test and submits the answers, no problem.
But, if the user navigates away from the page and returns to continue with the test, presently the 15 minutes restarts.

I already have timeLeft left function which records into a hidden form field.
My problem is; to be able to auto submit the timeLeft from  when the user leaves the page, so that the db is updated with the remaining time.

Sorry this is a long winded explanation.

How can I execute time submit onunload?
Avatar of Erikal

ASKER

Dear nanharbison,
I am really grateful for all the help I have been getting from Experts Exchange with different aspects of this online test.
I am now inches away from completing this project that i have been working on for the last three months. Being a novice at this game, I have never realised there I would discover so many pit holes that kept delaying the project.
If I can pass this final obstacle, I will be home amd dry.
I really would appreciate any help on this.
 I can pass on the relevant sections of the code if you think it is worth having a look at.

many thanks in advance for any help on this.
Oh, now I get it. You need to keep a session variable to hold the time left.
show the code on the page, especially the code that keeps track of the time.
Avatar of Erikal

ASKER

OK,
Here are the code sections to do with the time and time left event.

<?php // EngTest1.php
include("phpinclude/accesscontrol.php");
   dbConnect(mydb);
$sql="SELECT eng1comp FROM assess_reg WHERE userid='".$uid."'";
$result=mysql_query($sql);
if (!$result) {
        error('A database error occurred in processing your '.
              'submission.\\nIf this error persists, please '.
              'contact eric@lpf-learning.co.uk.');
//echo mysql_error()
    }
$row=mysql_fetch_assoc($result);
$EngStatus['eng1comp']=(int)$row['eng1comp'];
if ($EngStatus['eng1comp']==1){
      echo '<script language="javascript">confirm("You have already completed the English Test. Press OK to be directed to the Maths Test")</script>';
      echo '<script language="javascript">window.location  "http://ccgi.lpf.learning.co.uk/MathsTest1.php"</script>';
      exit;
}
else
{
      if ("Maths Test" !=strval($_POST['Submit_Eng1']))
      {
$sql="SELECT eng1time FROM assess_reg WHERE userid='".$uid."'";
$result=mysql_query($sql);
if (!$result) {
        error('A database error occurred in processing your '.
              'submission.\\nIf this error persists, please '.
              'contact eric@lpf-learning.co.uk.');
//echo mysql_error()
    }
$row=mysql_fetch_assoc($result);
$timeLeft=(int)$row['eng1time'];
    // Display the English Test form
    ?>
<!DOCTYPE html PUBLIC>
<html lang="en">
<head>
<title>English Test</title>
<script type="text/javascript">
var timeLeft = "<? echo $timeLeft; ?>";
var tId = "";
function countdown() {
       timeLeft -= 1000;
      if (timeLeft<=0){
      nextPage();
      } else {
      updateTimer();
   }
 }
window.onload=function() {
  tId = setInterval('countdown()',1000);
  updateTimer();
}
function updateTimer() {
   var timerArea = document.getElementById('timer');
   var remArea = document.getElementById('form1');
   var numSeconds = timeLeft / 1000;
   var displaySeconds = numSeconds % 60;
   var displayMinutes = (numSeconds - displaySeconds) / 60;
   // format display a little more by putting a leading 0 for small seconds
   if (displaySeconds < 10) {
       displaySeconds = "0" + displaySeconds;
   }
      timerArea.value = displayMinutes + ":" + displaySeconds;
      remArea.value = numSeconds*1000;
}
      function nextPage(){
            //assuming you have <form id="English1"...>
            var f = document.getElementById("English1");
            for( var i=0; i < f.elements.length; ++i)
            {
                    if( String(f.elements[i].type).toLowerCase() != "submit" )
                  f.elements[i].disabled=true;
            }
            clearInterval(tId);
            alert('Time allowed for the English test has expired! Please press the Maths Test button to continue');
      }
       function activate(f){
  if (timeLeft > 100000 && confirm('Are you sure you want to leave the English test? You still have some time left to go back and check your answers. If you are sure you want to go on to the Maths Test, please click OK button. Otherwise, click Cancel button to return to the English test and use the remaining minutes to improve your English score.'))
return false;
            for( var i=0; i < f.elements.length; ++i)
            {
                  f.elements[i].disabled=false;
            }
      return true;
      }
</script>

------------------------------------------------------------
Body onUnload event and form1 to capture the timeLeft when user leaves by refresh or back etc.
----------------------------------

<body text="#000000" style="background: #e5e5e5; text-align:center; height:2500px;" ONUNLOAD="window.document.getElementById('form1').submit()">
<form id="form1" method="GET" action="<? echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" id="eng1time">
</form>

--------------------------------------------------------------
script for passing form1.eng1time back to php
-----------------------

<?php
$timeLeft = $_GET['eng1time'];
$sql = "UPDATE assess_reg SET eng1time='".$_GET['eng1time']."' WHERE userid='".$uid."'";

    if (!mysql_query($sql))
        error('A database error occurred in processing your '.
              'submission.\\nIf this error persists, please '.
              'contact eric@lpf-learning.co.uk.\\n' . mysql_error());
Avatar of Erikal

ASKER

Hi again,
The code above works fine, except when passing the timeLeft variable from the form to PHP.
For some reason, no matter what the current value of the eng1time field (form1) onunload form1 passes integer value of zero to php ($_GET['eng1time']).
In fact this is the only problem, all the rest works fine.
Would you have any idea why this semms to be happening.
I even tried (int)$_GET['eng1time']), same problem.  
the form submit is not working. Maybe you should try storing the hidden value in a session variable. Are you familiar with sessions?

Avatar of Erikal

ASKER

This page is part of a session.
The php code I have for storing the hidden value which also updates the database with the new value is:
$timeLeft = $_GET['eng1time'];
$sql = "UPDATE assess_reg SET eng1time='".$_GET['eng1time']."' WHERE userid='".$uid."'";

How would I correctly store the hidden value in a session variable?
in the hidden field, you have this:
<input type="hidden" id="eng1time">

I am not positive about this, but I think you have to pass GET and POST variables by their name, not their id.
Can you try:
<input type="hidden" id="eng1time"  name="eng1time">
Avatar of Erikal

ASKER

Just tried it, same problem.

Do you think the unload event in body tag may be causing the problem?
On first page refresh I get zero
ASKER CERTIFIED SOLUTION
Avatar of nanharbison
nanharbison
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Erikal

ASKER

Dear nanharbison,
Thank you very much for your help.
At least I now know what the cause of the problem is. Upon your suggestion I have already posted a question in javascirpt zone.

Thanks again for isolating the error and pointing me in the right direction.