Prevent resubmit form after click “back” button

前端 未结 6 1827
情歌与酒
情歌与酒 2020-12-09 06:57

I have 2 pages :

page1.php :
- has a form with text box and a \"submit\" button. Eg :

相关标签:
6条回答
  • 2020-12-09 07:34

    You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern).

    Could be just a one-line if you've got the http_redirect function:

    http_redirect("page2.php");
    

    Instead of your javascript echo.

    If not, that are two lines:

    header("Location: http://example.com/page2.php");
    exit;
    

    Replace example.com with site's your hostname.

    Related: Back button re-submit form data ($_POST); I am confused about PHP Post/Redirect/Get

    0 讨论(0)
  • 2020-12-09 07:34

    Can you do it via an Ajax call instead? No action on the form, and the submit will call a the Ajax function. The Ajax call will execute the query, and provide a response (you can just echo a result), and you can then provide dynamic feedback based on the result. You'd never leave the page.

    <form id="thisForm">
    ...form input fields...
    <input type="button" onclick="return submitForm('thisForm')"/>
    </form>
    
    function submitForm(formId) {
        $.ajax( {
            type: "post",
            url: 'page2.php',
            data: $('#' + formId + ' input').serialize(),
            ... any other Ajax parameters...,
            success: function(data) {
            }
        });
        return false;
    }
    
    0 讨论(0)
  • 2020-12-09 07:36

    Add this code in the page that is showing as offline when the user clicks the back button:

    <?php
     session_start();
     header_remove("Expires");
     header_remove("Cache-Control");
     header_remove("Pragma");
     header_remove("Last-Modified");
    ?>
    
    0 讨论(0)
  • 2020-12-09 07:44

    Rather than

    echo '<script language="javascript">window.location="page2.php";</script>';

    you should use the header() function to redirect your user after the submission.

    So in psuedo code,

    click submit on page.php action page1.php page1.php submits data to database calls

    header('Location: http://example.com/page2.php');
    

    This should prevent your clicking back problem

    0 讨论(0)
  • 2020-12-09 07:47

    One way is to submit the Formdata via Ajax to a remote Script and if the Query returns success you can jump the a "Thank You" Page. So the User can hit the Back Button and the "Reload" Request doesn't pop up.

    Hope the Idea helps you

    0 讨论(0)
  • 2020-12-09 07:48

    Create a Session like shown here

    You should use session and validate the user from every page and you will amaze how SESSION works! AMAZING!

    0 讨论(0)
提交回复
热议问题