Brij Sharma
Brij Sharma

Reputation: 371

Auto submit form when user try to reload page or click on go back button

I am working on online exam portal when the user gives the exam I want to when the user tries to page reload or go back page, auto-submit the form with giving a warning message.

<script type="text/javascript">

  window.onload = function() {
    $('#form_id').submit();
   return true;

     // if I use alert here alert work but form not submitting

  };

  </script>

Upvotes: 1

Views: 1074

Answers (2)

Prasad Wargad
Prasad Wargad

Reputation: 765

Help taken from answer of @brk.
Reference Link: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Words related to stopping page reload: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Syntax

<?php
    echo '<br>GET PARAMETERS=<pre>'. print_r($_GET, true) .'</pre><br>';
?>
<html>
    <head>
        <title>Untitled Document</title>
    </head>
    <body onbeforeunload ='checkRequest(event)'>
        ABC
        <form name="frm1" id="frm1" action="">
            <input type="text" name="text1" id="text1" value="<?php echo ( isset($_GET['text1']) ? $_GET['text1'] : '' ) ?>">
        </form>
        <script type="text/javascript">
            function checkRequest(event){
                event.preventDefault();
                event.returnValue = '';
                var __type= event.currentTarget.performance.navigation.type;
                if(__type === 1 || __type === 0){
                    // alert("Browser refresh button is clicked...");
                    document.getElementById('frm1').submit();
                }
                else if(__type ==2){
                    alert("Browser back button is clicked...");
                }
            }
        </script>
    </body>
</html>

Upvotes: 0

brk
brk

Reputation: 50291

You can use onbeforeunload and event.currentTarget.performance.navigation.type

<body onbeforeunload ='checkRequest(e)'>
   //rest of code
</body>

function checkRequest(event){
   let __type= event.currentTarget.performance.navigation.type;
    if(__type === 1){
      // alert("Browser refresh button is clicked...");
   }
else if(__type ==2){
    //Browser back button is clicked
   }
}

You can also visit this link

Upvotes: 1

Related Questions