Close modal when page refreshes after an INSERT

1

I searched all corners of the internet but could not find anything like my problem. I have a registration form that after doing the INSERT in the database shows a modal window and inside it a success or error message along with an "OK" button. This works fine by pressing OK it closes the modal and displays the registration page again. My problem is that if the user before pressing "OK" gives an "F5" the "Confirm form resubmit" dialog box is displayed and if you click "Continue" it duplicates the INSERT and consequently the registration in the bank

HereisthePHPsummarycode:

if (isset($_POST['cadastrar'])) {

<!-- aqui vão os requires dos includes com os dados do banco-->

$sql = "INSERT";

$resultado mysqli_query($conexao, $sql) or die (mysqli_error($conexao));

$linhas = mysqli_affected_rows($conexao);

if($linhas > 0){

$mensagem = "Seu cadastro foi feito com sucesso!";

} else {

$mensagem = "Erro ao cadastrar!";

}

<!-- aqui vai o require include de desconexão-->

<!--o código abaixo chama a janela modal-->

?><script>$(document).ready(function() {
    $('#myModal').modal('show');
});</script>
<?php

}

?>

Below is the code for the modal window:

<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Mensagem:</h4>
      </div>
      <div class="modal-body">
        <p><?php echo"$mensagem"; ?></p> <!--exibe a mensagem de erro ou sucesso-->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Below are the scripts for fetching the bootstrap and jquery commands:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><!--Bancodecomandosparaexecutarajanelamodal-->
SobasicallywhatIwouldlikewasifyoupressKeysandF5whilethemodalwindowisdisplayed,theconnectiontothebankisclosedandyousimplydisplaytheregistrationpageandthemodaldisappears.Itriedtoputaheader("Location:") before the javascript that displays the modal, so it redirects the page, but it redirects but does not display the modal. I have already seen sites where this works, you do the registration and it is shown the modal, F5 and modal closes and does not ask for form resend.

All code is in the same file, if you need more data just ask. Thanks guys.

    
asked by anonymous 05.04.2017 / 19:20

2 answers

0

Well, more practical solution, test there, I did it quickly without testing. Basically, in the post if the insert occurs or the error, there will be the location with get send, if the page loads and has get open modal.

Throw archaic, but according to what you need.

<?php   
    if (isset($_POST['cadastrar']))
    {
        $sql = "INSERT";
        $resultado mysqli_query($conexao, $sql) or die (mysqli_error($conexao));
        $linhas = mysqli_affected_rows($conexao);

        if($linhas > 0)
        {

            //Redireciona e envia um GET
            echo 
            "
                <script>
                    location.href = 'arquivo.php?action=ok';
                </script>
            ";
        }
        else
        {

            //Redireciona e envia um GET
            echo 
            "
                <script>
                    location.href = 'arquivo.php?action=erro';
                </script>
            ";
        }
    }

    //Verifica se existe GET action
        if (isset($_GET['action']))
        {
            if($_GET['action'] =='ok'){

                $mensagem = "Seu cadastro foi feito com sucesso!";

            } else {

                $mensagem = "Erro ao cadastrar!";
            }
            echo 
            "
                <script>
                    $(document).ready(function() {
                        $('#myModal').modal('show');
                    });
                </script>
            ";
        }
?>
    
05.04.2017 / 19:38
1

Well actually your problem is in browser behavior when pressing the F5 key or even the refresh button. By default browsers redo the last executed operation, which in your case is a POST to the server.

By analyzing this problem superficially, the easiest way to prevent this situation would be to immediately redirect the user to another file only with the information to be displayed, because updating this page would have no effect on database. Using your own code, it would look like this:

Post.php file:

<?php
    if (isset($_POST['cadastrar'])) {

        <!-- aqui vão os requires dos includes com os dados do banco-->

        $sql = "INSERT";

        $resultado mysqli_query($conexao, $sql) or die (mysqli_error($conexao));

        $linhas = mysqli_affected_rows($conexao);

        <!-- aqui vai o require include de desconexão-->

        header('Location: exibe.php?linhas=' . $linhas);
    } else {
        echo 'Parâmetros incorretos.'
    }
?>

File show.php

<?php
    $linhas = $_GET['linhas'];

    if($linhas > 0){
        $mensagem = "Seu cadastro foi feito com sucesso!";
    } else {
        $mensagem = "Erro ao cadastrar!";
    }

    <!--o código abaixo chama a janela modal-->

?>
<script>
    $(document).ready(function() {
        $('#myModal').modal('show');
    });
</script>
    
05.04.2017 / 19:46