Check php and ajax

1

I have a form with an input type text and a button submit where I write a product code and search in a MySQL database.

I show the results in a table within the same page, but how do I make the page not be reloaded by pressing the search button? I have this code:

<table class="table table-hover">
    <tr>
        <th>Codigo</th>
        <th>Descripción</th>
    </tr>

    <?php 

    if (isset($_POST["btnBuscar"])) {
        $prod = new Productos();
        $cod = $_POST["txtCodProd"];
        $data = $prod->getProdByCod($cod);
        $var = '';

        if(!empty($data)){
            foreach ($data as $i=>$v) { ?>
              <tr>
                <?php $var .= "<td>".$v."</td>";
                 ?>

              </tr>
            <?php
                }
                echo "<tr>".$var."</tr>";
             ?>
    </table>
        <?php
        }else{
            echo 'No hay resultados.';
            }
        }
        ?>
</div>  

The Products driver has this function:

public function getProdByCod($cod){
        $p = new ProductosMySqlDAO();
        $res = $s->load($cod);
        return $res;
    } 

And the model:

    public function load($id){
        $sql = 'SELECT * FROM productos WHERE codigoproducto = ?';
        $sqlQuery = new SqlQuery($sql);
        $sqlQuery->setNumber($id);
        return $this->getRow($sqlQuery);
    }

    protected function getRow($sqlQuery){
        $tab = QueryExecutor::execute($sqlQuery);
        if(count($tab)==0){
            return null;
        }
        return $this->readRow($tab[0]);     
    }

Any suggestions on how to make that query with jquery?

    
asked by daniel 06.07.2016 в 21:58
source

1 answer

1
var codigo = $("input[name=codigo]").val();
$.get( "buscar.php", { codigo_producto: codigo } )
  .done(function( data ) {
    // data deberia ser un json (buscar.php debe retornar un json)
    alert( "Datos: " + data );
    // foreach de los datos, con la funcion append de jquery
    // puedes agregar facilmente items por medio de un id que le asignes a la tabla.
    $.each(data, function(i, item) {
      $("#table").append(/* aqui el <tr></tr>*/);
    });​
});

Use jquery and structure the JSON well that you return in buscar.php

    
answered by 06.07.2016 в 23:45