Pass search input to another file

Asked

Viewed 152 times

2

I am doing a car registration project, it is almost at the end, but when changing a bit the style file and tinkering the listing to leave in AJAX without refresh a bug strange happened, I have tried several ways to solve: the input where a search word can be typed does not send the data in any way to where the function should take it and show only the data that present the word.

Follows 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> 

Function list of JS:

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 into 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 the list function :

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

Making her like this:

function listar(){
    var palavra = document.getElementById('palavra');
    request = $.ajax({
        url: "/teste/services/automoveis.service.php?m=listar",
        type:'post',
        data: palavra,
    });
}
  • You have set within your form the Submit button pointing to the same page. So your form will call the same page in the middle of running your JS, and as JS runs on the client side, it will stop the execution. Try switching to $('form'). Submit() or change your type button from Submit to button

  • Another thing. The directory path /test/services/automoveis.service.php? m=list is different from test/services/automoveis.service.php? m=list. He is trying to fetch the test directory inside the root directory of his OS. Probably outside of his directory that apache le. That’s correct?

  • Bruno, thank you for your answer, I tried both ways, but none of them did. As for the url, it is working on all other functions, I created it at the root, outside of a default eclipse Workspace. I created it as /www/var/test

  • 1

    Try to take out the method and action that are declared duplicated in your form

  • 1

    After the date, try to enter success: function(data) {alert(data);}, error: function (error) { alert('deu erro');} if falling into Alert "gave error" has something wrong in your php, if it fell into Success is pq there is nothing wrong in your php

2 answers

1

The problem is that the form action will run before its javascript function.

Follow an example working the way you want 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>

backbackConsult.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));

0

Solved personal, thank you so much for the help. I ended up solving 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);
 });

}

Browser other questions tagged

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