Close modal when updating page after insert

Asked

Viewed 1,131 times

1

I searched every corner of the Internet but I couldn’t 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 a "OK" button. This works perfectly by pressing OK it closes the modal and again displays the registration page. My problem is that if the user before pressing "OK" gives a "F5" is shown the dialog box "Confirm form forwarding" and if you click on "Continue" it duplicates the INSERT and consequently the registration in the database.

Reenvio de formulário

Follow the short code of 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);

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 follows the modal window code:

<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 the scripts to fetch bootstrap and jquery commands:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="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> <!--Banco de comandos para executar a janela modal-->

So basically what I would like is for you to press F5 during the display of the modal window, the connection with the bank to be closed and simply show the registration page and the modal to disappear. I tried to put a header ("Location:") before the javascript that displays the modal, for it to redirect the page, but it redirects but does not display the modal. I’ve seen sites where this works, you register and is shown the modal, the F5 and the modal closes and does not request form forwarding.

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

2 answers

1

Good indeed your problem is in the behavior of the browser by pressing the F5 key or even the update button. By default browsers redo the last executed operation, which in your case is a POST to the server.

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

Post file.php:

<?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 displays.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>
  • Your example looked very similar to sNniffer and I think it should work, but passing the variable $lines to the other file did not work the way you put it. Anyway it can help a lot of people. Thank you!

  • You’re right! I edited the answer because I should have picked up the variable via GET. Now it’s ok.

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 upload, if the page loads and has the get opens the modal.

Kind of 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>
            ";
        }
?>
  • Really what I needed brother, it worked right! The only adaptation I did was to clone an onclick event on the modal button that redirected to the same page, because the variable "action" was still active and I had a search function on this page, that is, the modal appeared when pressing the button "Search". Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.