Search data using PHP and AJAX with jQuery

Asked

Viewed 157 times

0

Hello, I have an HTML page with a form, the form has 4 fields, on this page I want to fill the fields (randomly) and search the data according to what I filled.

For this I am using AJAX with jQuery, not to occur refresh, the searched data will be inserted in the same page. One of the rules is that when I search without entering any information, take place the search of all data from my database.

Today, if I click "Search" without filling in, I search all the information from my bank and present them on the screen, if I fill in some information and click Search, all the information is pulled equal.

The data searcher is a PHP file, which generates a JSON that is read by my search page, on this PHP page, for testing, I did an if to check if $_POST['pNome'] was empty, and it was empty, but I could not figure out why it was empty, and I have a similar registration screen working.

HTML code:

<!DOCTYPE html>
<html>
    <head>
        <title>Bootstrap com rodapé inferior</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="../../../_css/bootstrap.css" rel="stylesheet">
        <link href="../../../_css/estilo.css" rel="stylesheet">
        <script src="../../../_js/jQuery.js"></script>
        <script src="../../../_js/bootstrap.min.js"></script>
    </head>
    <body>
        <div id="wrapper" class="container-fluid">
            <div class="row">
                <div class="col-lg-2 col-lg-offset-5 col-md-2 col-md-offset-5 col-sm-4 col-sm-offset-4 col-xs-4 col-xs-offset-4" id="logo">
                    <img src="../../../_image/_logos/logo.png" class="img-responsive img-circle">
                </div>
            </div>
            <div class="row" >
                <nav class="navbar navbar-inverse">
                    <div class="container-fluid">
                        <div class="navbar-header">
                            <a class="navbar-brand" href="../../">Meu site</a>
                        </div>
                        <ul class="nav navbar-nav">
                            <li><a href="../../../">Home</a></li>
                            <li><a href="../../servicos/">Serviços</a></li>
                            <li><a href="../../contato/">Contato</a></li>
                            <li><a href="../../painel-administrativo/">Painel administrativo</a></li>
                        </ul>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a href="./"><span class="glyphicon glyphicon-log-out"></span> Logoff</a></li>
                        </ul>
                    </div>
                </nav>
            </div>
            <div class="body-content">
                <div class="row">
                    <form id="formPesquisaUsers">
                        <div class="col-lg-3 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-4 col-sm-offset-2 form-group">
                            <label for="matricula">Matricula</label>
                            <input type="tel" name="pMatricula" placeholder="Matricula" id="matricula" class="form-control">
                        </div>
                        <div class="col-lg-3 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-4 col-sm-offset-0 form-group">
                            <label for="nome">Nome</label>
                            <input type="text" name="pNome" placeholder="Nome" id="nome" class="form-control">
                        </div>
                        <div class="col-lg-3 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-4 col-sm-offset-2 form-group">
                            <label for="sobrenome">Sobrenome</label>
                            <input type="text" name="pSobrenome" placeholder="Sobrenome" id="sobrenome" class="form-control">
                        </div>
                        <div class="col-lg-3 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-4 col-sm-offset-0 form-group">
                            <label for="login">Login</label>
                            <input type="text" name="pLogin" placeholder="Login" id="login" class="form-control">
                            <input type="submit" value="Pesquisar" class="btn btn-block btn-primary margin15Top">
                        </div>
                    </form>
                </div>
                <div class="row" id="dadosPesquisados">

                </div>
            </div>
            <footer id="rodape">
                <div id="divRodape" class="col-lg-12 col-lg-offset-0">
                    <p>&copy; Conteúdo do rodapé</p>
                </div>
            </footer>
        </div>
        <script>
            $("#formPesquisaUsers").submit(function (e){
                e.preventDefault();
                var dadosForm = $(this);
                buscarDados(dadosForm);
            });

            function buscarDados(dados){
                $.ajax({
                    type: 'POST',
                    data: dados.serialize(),
                    url: "controllerPesquisaUsuarios.php",
                    async: false
                }).done(function(){
                    var dadosEncontrados = "";
                    $.getJSON("controllerPesquisaUsuarios.php", function(dadosJSON){
                        verificaBackground = false;
                        $.each(dadosJSON, function(i, valor){
                            if(verificaBackground){
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-2 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-1 divBackground'>";
                                dadosEncontrados += "Matricula: " + valor.idUsuario;
                                dadosEncontrados += "</div>";
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-0 divBackground'>";
                                dadosEncontrados += "Nome: " + valor.nome;
                                dadosEncontrados += "</div>";
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-1 divBackground'>";
                                dadosEncontrados += "Sobrenome: " + valor.sobrenome;
                                dadosEncontrados += "</div>";
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-0 divBackground'>";
                                dadosEncontrados += "Login: " + valor.login;
                                dadosEncontrados += "</div>";
                                verificaBackground = false;
                            } else {
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-2 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-1'>";
                                dadosEncontrados += "Matricula: " + valor.idUsuario;
                                dadosEncontrados += "</div>";
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-0'>";
                                dadosEncontrados += "Nome: " + valor.nome;
                                dadosEncontrados += "</div>";
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-1'>";
                                dadosEncontrados += "Sobrenome: " + valor.sobrenome;
                                dadosEncontrados += "</div>";
                                dadosEncontrados += "<div class='col-lg-2 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-5 col-sm-offset-0'>";
                                dadosEncontrados += "Login: " + valor.login;
                                dadosEncontrados += "</div>";
                                verificaBackground = true;
                            }
                        });
                        console.log(dadosEncontrados);
                        $("#dadosPesquisados").html(dadosEncontrados);
                    })
                }).fail(function(){
                    alert("erro");
                });
            }
        </script>
    </body>
</html>

PHP code:

<?php
    require_once '../../../_models/Conexao.php';
    require_once '../../../_models/Usuario.php';
    $con = new Conexao();
    $user = new Usuario($con->criaConexao());
    $info = $user->buscaUsuariosPorPesquisa($_POST['pMatricula'], $_POST['pNome'], $_POST['pSobrenome'], $_POST['pLogin']);
    echo json_encode($info);

NOTE: My $user object method is working correctly, yet I am providing the function to you.

Search function:

function buscaUsuariosPorPesquisa($matricula, $nome, $sobrenome, $login){
        try {
            $dados = ['idUsuario' => $matricula, 'nome' => $nome, 'sobrenome' => $sobrenome, 'login' => $login];
            $sql = "SELECT * FROM usuarios ";
            foreach ($dados as $key => $value) {
                if(!empty($value)){
                    if(!strpos($sql, "WHERE")){
                        $sql .= "WHERE ";
                    }
                    $sql .= "{$key} = '{$value}' ";
                    if(!empty(next($dados))){
                        $sql .= "AND ";
                    }
                } else {
                    if(!empty(next($dados)) && strlen($sql) > 29){
                        $sql .= "AND ";
                    }
                }
            }

            $st = $this->conexao->prepare($sql);
            $st->execute();
            $st->setFetchMode(PDO::FETCH_OBJ);
            return $st->fetchAll();
        } catch (Exception $ex) {
            return $ex;
        }
    }

My conclusion is that my PHP page has the $_POST variables all empty, but why?

Thanks for your help

1 answer

0

Print your data variable in javascript after serialize.

console.log(dados);

Probably gonna show something like

single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

If you send this to PHP as a POST, it will all go in one string. You must send an object.

{
   'chave1': 'valor1',
   'chave2': 'valor2'
}

In PHP, print the $_POST variable.

var_dump($_POST);

And see what you’re getting.

Search on serializeArray, or data types in JSON with Ajax you should find an answer.

  • Hello Éverton, sorry for the delay, I ended up having to distance myself from this project, but working on other projects I found a solution, jQuery’s $.post function, I recommend who is having similar problem studying the same. Documentation: https://api.jquery.com/jQuery.post/

Browser other questions tagged

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