Send form without refresh and bring results to the same page

Asked

Viewed 415 times

0

I need to submit a POST form to make a query on a PHP page (dashboard.php) and return the results of that query, on that same page of the form (refresheless), how could you do?

I imagine I’ll have to use Ajax, but I don’t know how...

The code I have, it’s working, I’ve used SESSION, however, is giving refresh on the page.

HTML: (dashboard.php)

    <form method="post" action="verificar-painel-admin.php">
        <input type="text" name="usuario" value="joaozinho" readonly>
        <button type="submit" name="confirm_usuario_pedido">Clique aqui para consultar os pedidos desse usuário.</button>
    </form>
        
        <p> 
            <div class="card-deck">
                <?php
                    // Exibindo os pedidos do cliente caso haja.
                    if(isset($_SESSION['msg_pedidos_usuario'])){
                    echo $_SESSION['msg_pedidos_usuario']; 
                    unset($_SESSION['msg_pedidos_usuario']);}
                ?>
            </div>
        </p>
    

PHP: (check-panel-admin.php)

 if(isset($_POST['confirm_usuario_pedido'])){
    $cliente = $_POST['cliente'];

    // Todos os pedidos do usuário 
    $sql = mysqli_query($con,"SELECT ID_compras FROM usuarios_pedidos WHERE usuario = '$cliente'");
    $qnt_pedidos = mysqli_num_rows($sql);

        // Se existir pedido desse usuário, exibir.
        if ($qnt_pedidos > 0) {

            while ($cont = mysqli_fetch_array($sql)){

            $_SESSION['msg_pedidos_usuario'] = "Você possui ". $qnt_pedidos . "pedidos";

            }  } // End IF & While 

        else{
             $_SESSION['msg_pedidos_usuario'] = "<h4>Você ainda não possui pedidos!</h4>"; 
        } 

    header("Location: painel-admin.php");
  }

1 answer

1


Hello, yes you will have to use AJAX for such task. I saw that you set jquery, so I will use it in this example.

Since you didn’t display your form page, I’ll tell you what I think should be done.

  • PHP:
  1. Create a file to handle this backend: seu_arquivo.php

  2. Configure the file, and treats to prevent users from accessing this file directly from the browser (I usually send post by ajax, and do a if(!$_POST){ header('location: ...') })

  3. Once you’ve done all the Insert of your form, you’ll have to make a select to have this data ready for display(an interesting way is the PDO::lastInsertId()),

  4. With the data ready, you can choose to generate a json with this data or already display in HTML, within tags and tals (in json is the most current way), and after that echo with the data, exit the file.

  • Javascript
  1. Send the form to the backend by ajax. As you said you do not know how, I will make an example:

    var dados = $('seu_formulario').serialize() // serialize() pega todos os valores dos inputs filhos do formulario no seletor
    
    // função post(), vai fazer a requisição ajax
    // primeiro parametro é a url,
    // segundo é referente aos dados do seu form a serem enviados, 
    // terceiro é como vc vai lidar com o retorno
    $.post(
        'seu_arquivo.php',
        dados,
        function(respostaAjax){
            // aqui que vai rolar a exibição, é interessante fazer uma validação antes,
            // voce pode dar um echo 'ERRO' no php e ler esse erro aqui, e exibir pro usuario
            if(respostaAjax == 'ERRO') {
                alert('ERRO blabla...'); // sua tratativa de erro
    
            } else {
                // vamos supor que você resolveu dar echo no html pronto
                $('sua_div').html(respostaAjax) // pronto, sua div vai ter os dados do backend sem nenhum refresh
                // se você resolveu fazer com json, pode dar um JSON.parse(respostaAjax) e então ir modificando
            }
        } 
    

In a nutshell, that is, if I have any doubts, I am willing, I hope I have helped!!

  • Thank you so much for the answer! but unfortunately I am layman with ajax, json, etc..., I don’t really know how to do it. If it’s not too much to ask, wouldn’t you be able to give more detailed examples based on my code? Since how I send the data from form, until the recovery of the same?

  • No problem, there is, but is there any way we can talk through a chat? Because it will probably be very long

  • I don’t think I got enough scores

  • And I don’t know how to make kkkk has my Linkedin in my profile, sends me a message there and we try to see it there

  • 1

    Good Answer, there are also other libraries like Axios or you can call natively with Xmlhttprequest or with the new fetch().

Browser other questions tagged

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