Mysql query return with PHP+Javascript

Asked

Viewed 173 times

0

I’m creating a PHP query in a Mysql database. So far so good. The query works fine. I’m calling the query from a javascript using $.post('pagina.php',meusparametros,function(resultado){}) to insert the search result into my html page. I can even see the result appear in html when I do the test. The problem is that in the sequence it seems that the page gives a "refresh"... then add everything. =(

However, if I "print" the while for example in an Alert that is, it shows me the search result...

js file.

$(function(){    
    $("#btnPesquisa").click(function(){
        var usr = $("#idUsr").val();
        var dti = $("#dtinicio").val();
        var dtf = $("#dtfinal").val();
        if(usr != ""){
            var sDados = {
                usuario : usr,
                dtinicio : dti,
                dtfinal : dtf
            }
            $.post('pesquisa.php',sDados,function(retorno){
                $(".resultado").html(retorno);
            });
        }else{
            $(".resultado").html('');
        }
    });
});

php search.

require "conexao.php";
require "Usuario.class.php";
try{
    $usr = $_POST['usuario'];
    $dti = $_POST['dtinicio'];
    $dtf = $_POST['dtfinal'];
    $u = new Usuario();
    $sDados = $u->pesquisaAcessos($usr,$dti,$dtf);
    while($result=$sDados->fetch()){
        echo '<li>'.$result['ocorrencia'].'</li>';
    }
}catch(Exception $e){
    echo '<script text="text/javascript"> alert("'.$e->getmessage().'")</script>';
}

html page.

    <article class="cam-article">    
        <form class="menu-form" name="pesquisa" id="pesquisa" action="" method="POST">
            <div class="menu-card">
                <div class="menu-div-bar card-group">
                    <input type="text" id="idUsr" name="usuario" placeholder="Digite o nome do usuário">
                </div>
                <div class="menu-div-bar card-group">
                    <input type="date" id="dtinicio" name="dtinicio">
                </div>
                <div class="menu-div-bar card-group">
                    <input type="date" id="dtfinal" name="dtfinal">
                </div>
                <div class="menu-div-bar card-group">
                    <button type="submit" class="menu-btn" name="btnPesquisa" id="btnPesquisa">PESQUISAR</button>
                </div>
            </div>
        </form>
        <article class="cam-article">
            <ul class="resultado">
            </ul>
        </article>
    </article>
  • Show btnPesquisa code, it is probably sending the form.

  • Excuse me, I edited the question there, I do not know if this is how you do, I am new here in the forum... Tks!

3 answers

1

When you click on the "Submit" button it sends the form, then after executing the onClick function the page is reloaded, a solution is the preventDefault() your js code would be:

$("#btnPesquisa").click(function(event){
    event.preventDefault(); // função que impede o envio do form,  evento padrão
    var usr = $("#idUsr").val();
    var dti = $("#dtinicio").val();
    var dtf = $("#dtfinal").val();
    if(usr != ""){
        var sDados = {
            usuario : usr,
            dtinicio : dti,
            dtfinal : dtf
        }
        $.post('pesquisa.php',sDados,function(retorno){
            $(".resultado").html(retorno);
        });
    }else{
        $(".resultado").html('');
    }
});

Another way would be to simply delete the html tag form.

0

The problem is that when clicking the button, in addition to the call from $.post also made the form’s Ubmit. In the case as the action is null, it seems to 'fade all'.

There are 3 ways to solve this:

  1. Withdraw the type='submit' button and remove the form.

  2. Insert event.preventDefault(); in javascript as other answers cited.

  3. Set the form action to pesquisa.php and maintain the type='submit' from the button. There you no longer need javascript. The data is already sent directly to php. But then.php search needs to return a valid HTML page and not just the results.

Edit

For o3 just change PHP to:

require "conexao.php";
require "Usuario.class.php";
try{
    $usr = $_POST['usuario'];
    $dti = $_POST['dtinicio'];
    $dtf = $_POST['dtfinal'];
    $sDados = $u->pesquisaAcessos($usr,$dti,$dtf);
    echo "<html><body><ul>";
    while($result=$sDados->fetch()){
        echo '<li>'.$result['ocorrencia'].'</li>';
    }
    echo "</ul></body></html>";
}catch(Exception $e){
    echo '<script text="text/javascript"> alert("'.$e->getmessage().'")</script>';
}

and remove all javascript

  • Nelson, thank you so much! for the help, I will research more on option 3 of your reply. If you can exemplify, I am grateful! Thanks for the tips!

0


what is happening to your code is that you are giving a Submit in your form, by default Submit makes a redirect to the path that is pointed in action of your form. And how the action your form is empty by default it redirects to the page itself. You solve this in two ways:

Modify the type of <button>

Of:

<button type="submit" class="menu-btn" name="btnPesquisa" id="btnPesquisa">PESQUISAR</button>

To:

<button type="button" class="menu-btn" name="btnPesquisa" id="btnPesquisa">PESQUISAR</button>

or you can add the command event.preventDefault() in the JS function:

$("#btnPesquisa").click(function(event){

    event.preventDefault();

    var usr = $("#idUsr").val();
    var dti = $("#dtinicio").val();
    var dtf = $("#dtfinal").val();
    if(usr != ""){
        var sDados = {
            usuario : usr,
            dtinicio : dti,
            dtfinal : dtf
        }
        $.post('pesquisa.php',sDados,function(retorno){
            $(".resultado").html(retorno);
        });
    }else{
        $(".resultado").html('');
    }
});
  • Fabio, thanks for the help! Changing the type <button> really solved! Thanks, however Event.preventDefault(); no effect. Thanks so much for the help"

Browser other questions tagged

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