AJAX: Send value to php file, query using this value, and returnate a Json array

Asked

Viewed 561 times

1

Can anyone help me with this code? Why doesn’t it work? I am trying to send a value received by a form to a php file, use this value in my SQL query searching for records that contain this value, return a Json array with the result(s) and print them on the screen using html.

My Query SELECT:

$sql= "SELECT * FROM incidente WHERE (titulo LIKE '%':buscar'%' OR descricao LIKE '%':buscar'%')";

//...

$recebeConexao->bindParam(':buscar', $_POST['busca'], PDO::PARAM_STR);

HTML code:

<!-- here I am creating a form whit text input and a button that call the function enviar() -->

<form id="buscar">
  <input id="busca" name="busca" type="text" placeholder="Buscar incidente" />
  <input onclick="enviar()"  type="button" value="ok" />
</form>

<!-- creating a array that will receive values from SQL consult -->

<div id="content" class="content">   
  <article class="underline">\
    <a href="incidente.html"><img id="incidente"\ 
      src="img/buraco.jpg" alt="Incidente" /></a>\
    <h2><a href="basic_markup.html" id="tit">'+tit+'</a></h2>\
    <p id="desc">'+desc+'</p>\
    <div class="date" id="date">'+dateVal+'</div>\
    <img class="tick" alt="não resolvido" src="img/no-tick.png">\
    <img class="apoio" alt="apoiar" src="img/apoio.png">\
  </article>'
</div>

Send function():

function enviar() {
  function viewData(data, el) {
    var content = '';
    for (var i in data) {
      var tit = data[i].titulo;
      var desc = data[i].descricao;
      var dateVal = data[i].data;
      content += '<article class="underline">\
        <a href="incidente.html"><img id="incidente"\ 
        src="img/buraco.jpg" alt="Incidente" /></a>\
        <h2><a href="basic_markup.html" id="tit">'+tit+'</a></h2>\
        <p id="desc">'+desc+'</p>\
        <div class="date" id="date">'+dateVal+'</div>\
        <img class="tick" alt="não resolvido" src="img/no-tick.png">\
        <img class="apoio" alt="apoiar" src="img/apoio.png">\
       </article>';
    }
    $('#'+el).html(content);
  }
  $(function(){
    $.ajax({
      var formula = $('#buscar').serialize();
      type: "POST",
      data:formula,
      url: "http:/ip/connect/www/buscar.php",
      dataType: "json",
      success: function (data) {
        viewData(data,'content');
      }
    });
  });
}

I’m getting the bug: enviar is not defined...

  • 3

    Where on the page you are declaring the function enviar();? This error is because the page is trying to call a function that does not exist or has not yet been declared.

  • viewData() is set within enviar()? What’s the problem json isn’t enough? your query returns nothing?

  • You placed the function viewData inside the send function, and called the Viewdata function without calling the send function. So it is the same as saying that the function viewData did not exist. And gives error.

3 answers

1

1) Call from Funcao search

   $habilitado = 's';$pesquisa_T = "paulo tarciso";
   $vai_T = pesquisa($pesquisa_T,$habilitado);

2) Function search

    function pesquisa($pesquisa_T, $habilitado){
        $pdo = conectar("conexao com Banco de Dados");
       $pesquisa = $pdo->prepare("SELECT * FROM itens_coluna
            WHERE (dsc_noticia LIKE CONCAT('%',:Oque,'%') OR
                  titulo LIKE CONCAT('%',:Oque,'%')) AND
                  habilitado = :habilita");

  $pesquisa->bindParam(":Oque",$pesquisa_T, PDO::PARAM_STR);
  $pesquisa->bindParam(":habilita",$habilitado, PDO::PARAM_STR);
  $pesquisa->execute();
  return $pesquisa->fetchAll(PDO::FETCH_OBJ);
    }

1

1) Check to see if there is a declaration of the tag <script>, for your javascript code. Just as if your query returns values and mainly format the query return turning it into Json.

2) When you call an event onclick: onclick="enviar()", this method is expected to return something to you (true/false).

In this case, I recommend some modifications:

HTML:

<form id="buscar">
  <input id="busca" name="busca" type="text" placeholder="Buscar incidente" />
  <input id="btnBuscar" type="button" value="ok" /> <!-- Retirada do evento onclick e adição de id ao botão. -->
</form>

Javascript:

function viewData(data, el) {
    var content = '';
    for (var i in data) {
      var tit = data[i].titulo;
      var desc = data[i].descricao;
      var dateVal = data[i].data;
      content += '<article class="underline">\
        <a href="incidente.html"><img id="incidente"\ 
        src="img/buraco.jpg" alt="Incidente" /></a>\
        <h2><a href="basic_markup.html" id="tit">'+tit+'</a></h2>\
        <p id="desc">'+desc+'</p>\
        <div class="date" id="date">'+dateVal+'</div>\
        <img class="tick" alt="não resolvido" src="img/no-tick.png">\
        <img class="apoio" alt="apoiar" src="img/apoio.png">\
       </article>';
    }
    $('#'+el).html(content);
  }
$("#btnBuscar").click(function() { //Retirada de função sem retorno "Enviar" e adição de evento para capturar o click do botão com id "btnBuscar"
    $.ajax({
      var formula = $('#buscar').serialize();
      type: "POST",
      data:formula,
      url: "http:/ip/connect/www/buscar.php",
      dataType: "json",
      success: function (data) {
        viewData(data,'content');
      }
    });
  });

I think you’ll resolve....

  • Actually solved the serialize(var formula = $('#fetch').serialize();) was inside the ajax and would have to stay before... Thanks!!

1

Try it like this:

var enviar = function() {
  viewData : function(data, el) {
    var content = '';
    for (var i in data) {
      var tit = data[i].titulo;
      var desc = data[i].descricao;
      var dateVal = data[i].data;
      content += '<article class="underline">\
        <a href="incidente.html"><img id="incidente"\ 
        src="img/buraco.jpg" alt="Incidente" /></a>\
        <h2><a href="basic_markup.html" id="tit">'+tit+'</a></h2>\
        <p id="desc">'+desc+'</p>\
        <div class="date" id="date">'+dateVal+'</div>\
        <img class="tick" alt="não resolvido" src="img/no-tick.png">\
        <img class="apoio" alt="apoiar" src="img/apoio.png">\
       </article>';
    }
    $('#'+el).html(content);
  }
}
  $(function(){
    $.ajax({
      var formula = $('#buscar').serialize();
      type: "POST",
      data:formula,
      url: "http:/ip/connect/www/buscar.php",
      dataType: "json",
      success: function (data) {
         enviar.viewData(data,'content');
      }
    });
  });

Browser other questions tagged

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