Pass the search input to another file

2

I'm doing a car registration project, it's almost at the end, but by altering the style file a bit and tinkering with the list to leave AJAX without refresh a bug strange happened, I've already tried several ways to solve : input where a search word can be typed does not send the data in any way to where the function should get it and only display the data that has the word.

Follow the code:

HTML:

<form action="" method="POST" style="top:12%; left:13px; position:absolute; width:50%" name="frmBusca" method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>?m=listar" >
    <input type="text" name="palavra" id="palavra     "placeholder="Pesquisar"class="text_busca" />
    <input type="submit" id="buscar" class="btn_busca" value="Buscar" onClick="listar()" />
</form> 

JS list function:

function listar(){
    request = $.ajax({
        url: "/teste/services/automoveis.service.php?m=listar",
        type:'post',
    });
}

PHP:

function mostra(){  
    $palavra = '';
    if(isset($_POST['palavra'])){
        $palavra = $_POST['palavra'];
    }
    $banco = "automoveis";

    $conexao = conecta();
    if($conexao){
        $db=mysqli_select_db($conexao, $banco);
    } else {
        echo ("Erro ao conectar ao bando de dados");
        return false;
    }

    echo $palavra;
    $String = "SELECT descricao,placa,codigoRenavam,anoModelo,anoFabricacao,cor,km,marca,preco,precoFipe, id FROM automovel ";
    if($palavra != ''){
        $String .= "WHERE descricao LIKE '%".$palavra."%' OR placa LIKE '%".$palavra."%' OR codigoRenavam LIKE '%".$palavra."%' OR anoModelo LIKE '%".$palavra."%' OR anoFabricacao LIKE '%".$palavra."%'
OR cor LIKE '%".$palavra."%' OR km LIKE '%".$palavra."%' OR marca LIKE '%".$palavra."%' OR preco LIKE  '%".$palavra."%' OR precoFipe LIKE  '%".$palavra."%' ";
    }
    $String .= "ORDER BY descricao ";
    $sql = mysqli_query($conexao, $String);
    $ar_info = array();
    while($exibe = mysqli_fetch_assoc($sql)){
        error_log(print_r($exibe, true));
        $ar_info[] = $exibe;
    }
    echo json_encode($ar_info);

}

What I've already tried:

Add this HTML page code to a script tag:

<script type="text/javascript" >    
    $("#buscar").click(function(){
        var palavra = $("#palavra").serialize();
        console.log(palavra);
        if( $("#palavra").val() != '') {
            console.log($("#palavra").val())
        }
    });
</script>   

Add to list function:

var palavra = document.getElementById('palavra');

Making it look like this:

function listar(){
    var palavra = document.getElementById('palavra');
    request = $.ajax({
        url: "/teste/services/automoveis.service.php?m=listar",
        type:'post',
        data: palavra,
    });
}
    
asked by anonymous 26.07.2017 / 14:55

2 answers

1

The problem is that the form's action will be executed first rather than its javascript function.

Here's an example working the way you want it in the question:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script>$(document).ready(function(){$("form").submit(function(event) {
                    $.ajax({
                        url: 'retornaConsulta.php',
                        data: $(this).serializeArray(), // pega os dados de todos os inputs do formulario
                        dataType: 'json',
                        type: 'post',
                        beforeSend: function() {
                            alert("antes de enviar a requisição ajax");
                        },
                        success: function(retorno) {
                            if (retorno.success) {
                                alert("CONTEUDO PESQUISADO: " + retorno.conteudoPesquisado);
                            }
                            else {
                                alert("NENHUM REGISTRO ENCONTRADO!");
                            }

                        },
                        complete: function() {
                            alert("depois de enviar a requisição ajax");
                        },
                        error: function() {
                            alert("ocorreu algum erro ao enviar a requisição ajax");
                        }
                    });

                    // necessário para não executar o action do formulario
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <form>
            <input type="text" name="pesquisa" value=""/>
            <input type="submit" value="Pesquisar"/>
        </form>
    </body>
</html>

returnConsult.php

<?php

$conteudoParaPesquisa = filter_input(INPUT_POST, "pesquisa", FILTER_SANITIZE_STRING);

// Aqui vai toda sua lógica

// Dados que você vai retornar para seu ajax
echo json_encode(array("success" => "true", "conteudoPesquisado" => $conteudoParaPesquisa));
    
26.07.2017 / 15:34
0

Solved, thank you very much for the help. I ended up solving it in a somewhat different way:

HTML:

 <form class="frmBus" style="width:50%" name="frmBusca">
     <input type="text" name="palavra" id="palavra" placeholder="Pesquisar" class="text_busca" />
     <input type="button" id="buscar" class="btn_busca" value="Buscar" onClick="listar()" /> 
 </form>    

JavaScript:

 function listar(){
     var palavra = $("#palavra").val();
     request = $.ajax({
     url: "/teste/services/automoveis.service.php?m=listar",
     type:'post',
     data: "palavra=" + palavra
 });

 request.done(function (response, textStatus, jqXHR){
     console.log(response);
     var obj = jQuery.parseJSON(response);
     getList(obj);
 });

}
    
27.07.2017 / 14:49