Show success message without leaving the page

Asked

Viewed 905 times

0

I have a form that sends some data to the database and uploads it to an FTP, the bank part has a if which returns the error in a variable and shows the error in the form itself. But my question is how do I do it for another type of error ? Follow the code below:

$query = "INSERT INTO ".$table." (versao, revisao, data) VALUES 
('".$versao."', '".$revisao."', '".$data."')";
$resultado= mysqli_query($conn, $query);


if(mysqli_insert_id($conn)){
    $_SESSION['msg'] = "<div class='alert alert-success'>Versão e Revisão cadastrada com sucesso!</div>";
}else{
    $_SESSION['msg'] = "<div class='alert alert-danger'>Erro ao cadastrar ao cadastrar Versão e Revisão!</div>";
} 

This is the example that stores in a variable and displays in a part of the HTML form.

<div class="container">

<?php
    if(isset($_SESSION['msg'])){
        echo $_SESSION['msg'];
        unset($_SESSION['msg']);
    }
?>

How could I do for this message I manage to display on the form page instead of going to another page to show the message ?

if ( @ftp_put( $conexao_ftp, $destino, $arquivo_temp, FTP_BINARY ) ) {
// Se for enviado, mostra essa mensagem
    echo '<br> <p class="alert alert-success d-flex justify-content-center"> Arquivo enviado com sucesso! </p>';

} else {
// Se não for enviado, mostra essa mensagem
    echo '<br> <p class="alert alert-danger d-flex justify-content-center"> Erro ao enviar arquivo! </p>';
}

Como nesse exemplo que mostra a mensagem acima do formulário

  • In php not to be done, you will have to use ajax.

  • the way it is there in the example that has $_SESSION['msg'] = , wouldn’t have something like that ? I tried to do this one and it didn’t work. Or in this case there is by is within a session ?

  • You can’t do that. Only with php you could not change the content of the page, you need to use javascript, with ajax, I suggest you study this better to implement. I did a little research and that here can help, it is a tutorial that creates a php register with ajax.

2 answers

2

Since php only runs on the server side, the information arrives on the server, it gives you a feedback, and the page loads. You will need to use my friend ajax.

Use the upload method (I’m using jquery in this case):

<script>
function enviarDados(){
    $.ajax({
     method: "POST",
     url: "seuarquivo.php",
     data: { versao: $("#versao").val(), revisao: $("#revisao").val(), data: $("#data").val() },
     function(msg){
       $("#resultado").html(msg);
       // #resultado é um id de um elemento de texto, como <p> ou <span>
       //quando você der echo na outra página, ele virá como parâmetro para essa função aqui.
     }
    });
  }
</script>

In the data you pass an object with key and value of the variables that will be sent.

In his form you can put a click event on the button, something like:

<button onclick="enviarDados();">Salvar</button>

Your php can stay as it is, you will only assign to variables the data that will arrive via post. You’ll need a strategy to get the data. Usually, I take the .val() of input and put into a variable, versao for example. Remember to put echo in your php.

There are other methods that use ajax, such as $.post. Read more here

  • By doing with AJAX, the only thing that will refresh on the page will be my message of success or error ? And how would I show the message ?

  • I edited with the answer

  • 1

    Note that $.ajax is a function of the jquery library, so if you haven’t already imported it into the project, you’ll have to.

  • Instead of me putting the action=teste.php, I would leave blank and the action would be done by the onclick of the button ?

  • That, you will need jquery, or change the function to getElementById

  • You will need to take the action, and I recommend changing the input from type Submit to a same <button> .

  • So, on the form page I put this code you gave me, then in my php I left it like this (http://prntscr.com/li8fvm), the page appears that you are making the secure connection and so on, but it clears the form fields and does not send anything, I have to change something else in php ?

Show 2 more comments

2


<?php
session_start();

// Verifica se o "dados" está configurado, se sim significa q o form foi submetido(enviado)
if ( isset($_POST['dados']) ) {

    $query = "INSERT INTO ".$table." (versao, revisao, data) VALUES ('".$versao."', '".$revisao."', '".$data."')";

    $resultado= mysqli_query($conn, $query);

    if(mysqli_insert_id($conn)) {
      $_SESSION['msg'] = "<div class='alert alert-success'>Versão e Revisão cadastrada    com sucesso!</div>";
    }else{
      $_SESSION['msg'] = "<div class='alert alert-danger'>Erro ao cadastrar ao cadastrar  Versão e Revisão!</div>";
    }

    if ( @ftp_put( $conexao_ftp, $destino, $arquivo_temp, FTP_BINARY ) ) {
      // Se for enviado, mostra essa mensagem
      $_SESSION['msg2'] = '<br> <p class="alert alert-success d-flex justify-content-center"> Arquivo enviado com sucesso! </p>';

    } else {
        // Se não for enviado, mostra essa mensagem
       $_SESSION['msg2'] = '<br> <p class="alert alert-danger d-flex justify-content-center"> Erro ao enviar arquivo! </p>';
    }

} // fim do if

?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Seu form</title>
    </head>
    <body>

        <?php

            // Mostra a msg q está na variável global $_SESSION
            if(isset($_SESSION['msg'])){
                echo $_SESSION['msg'];
                unset($_SESSION['msg']);
            }

            if(isset($_SESSION['msg2'])){
                echo $_SESSION['msg2'];
                unset($_SESSION['msg2']);
            }

        ?>

        <!-- Deixe o action vazio para que os dados sejam enviados para propria página  -->
        <!-- Isso resolve o seu problema de sair da página -->
        <form method="post" action="">

            <!-- crie um input do tipo hidden(oculto) para sinalizar que os dados do form foram enviados -->
            <input type="hidden" name="dados">


        </form>

    </body>
</html>
  • 1

    Aahh I think I got it, so this $_SESSION variable is actually a php function that works within a login ?

  • It is a 'superglobal', or global automatic, variable. This simply means that it is available in all scopes by the script.

  • Using this method, it will return me the message in the form itself, but it will redirect to a blank page that would be my php, then when I go back to the form page, appears the message, the only one to continue on the page would be using ajax to send the data as the friend above said, right ?

  • You can send the data to another file. php and then redirect to the form page again with: echo "<script> Location.href = 'seuform.php'; </script>";

Browser other questions tagged

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