Returning linked data

Asked

Viewed 58 times

3

With the help of Milrak Pereira Pessoa and Wéllingthon M. de Souza, I edited my code... I have a product code and it has 5 types and 5 descriptions. I am trying to bring to the user the types and descriptions within the blank table. However, the way I’m trying it adds lines below the table that only has 5 lines as in the image below

inserir a descrição da imagem aqui

Photo 1 => Records in the database, wanted the numbers to be returned within a table to display them to the user

inserir a descrição da imagem aqui

index php.

<!-- Inicio do script criado para função de completar próximos campos -->
<script type='text/javascript'>
    $(document).ready(function(){
            $("input[name='descri']").blur(function(){
                    var $codigo_produto = $("input[name='codigo_produto']");
                    var $id = $("input[name='id']");
                    var $codigo_tipo = $("input[name='codigo_tipo[]']");
                    var $descricao = $("input[name='descricao[]']");                       

                    $.getJSON('function.php',{ 
                            descricao: $( this ).val() 
                    },function( json ){
                            var html = "";
                                for (var i = 0; i < json.length; i++) {
                                  html += '<tr>';
                                    html += '<td><input type="hidden" name="id[]" value="'+json[i].codigo_produto+'"></td>';
                                    html += '<td><input type="text" name="codigo_tipo[]" value="'+json[i].codigo_tipo+'" /></td>';
                                    html += '<td><input type="text" name="descricao[]" value="'+json[i].descricao+'" /></td>';
                                  html += '</tr>';
                                }

                            $("table tbody").append(html);
                    });
            });
    });
</script>  
<!-- Fim do script -->

<form action='salvar.php' method='POST'>   

    <div class='form-group col-lg-4'>
        <label>  <b>Descrição:</b> </label> <!-- Não é enviado para o banco só está sendo utilizado para preencher os campos a partir deste -->
        <input type="text" maxlength="20"  name="descri"><br><br>
    </div>
    <div class='form-group col-lg-4'>
        <label>  <b>Código do Produto:</b> </label>
        <input type="text" maxlength="15"  name="codigo_produto"><br><br>
    </div>

    <table border="2"><!-- Iniciando a Tabela -->

        <thead>
            <tr><!-- Início dos Títulos da Tabela / Cabeçalho -->
                <th>Tipo</th>
                <th>Descrição</th>                                                                                                              
            </tr><!-- Fim dos Títulos da Tabela / Cabeçalho -->
        </thead>

        <tbody>
        <?php for($i = 1; $i <= 5; $i++){ //coloquei este valor para testar ?>        
                <tr>
                    <?php              
                        $sql_tipo = "SELECT * FROM tipoprod ";
                        $resulta = $conn->query($sql_tipo);
                        $row = $resulta->fetch_assoc();
                            echo '<td><input type="hidden" name="id" value="'.$row['id'].'"></td>';
                    ?> 
                    <td><input type="text" name="codigo_tipo[]"</td>
                    <td><input type="text" name="descricao[]" </td> 

                </tr>
           <?php } ?>
        </tbody>

    </table><br>

Function.php

  <?php
include_once("conn.php");

function retorna($descricao, $conn){

    $result = "SELECT A.descricao, A.codigo_produto, B.codigo_tipo, B.descricao FROM CADPRO A "
            . " LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO) WHERE A.descricao= '$descricao' ";

    $resultado = mysqli_query($conn, $result);

    // DECLARA A VARIAVEL
    $valores = array();

    if($resultado){
        while( $row = mysqli_fetch_assoc($resultado)){

            $novo['codigo_produto'] = $row['codigo_produto'];
            $novo['codigo_tipo'] = $row['codigo_tipo'];
            $novo['descricao'] = $row['descricao'];

            array_push($valores, $novo);
        }

    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));        
    }

    return json_encode($valores);                
}

if(isset($_GET['descricao'])){
    echo retorna($_GET['descricao'], $conn);
}
?>
  • Edit the question and put the return json

  • the feedback I’m getting inside the network tab ? I’ll edit and put

  • Do you want to replace the existing data in the table ? Or add the rows at the end of the table ?

  • i want the user to enter the product description, it returns the product code and also the types and descriptions linked to it

2 answers

1

Only returns an error on account of your While:

 while( $row = mysqli_fetch_assoc($resultado)){         
     $valores['codigo_produto'] = $row['codigo_produto'];
     $valores['id'] = $row['id'];
     $valores['codigo_tipo'] = $row['codigo_tipo'];
     $valores['descricao'] = $row['descricao'];
    }      

Every time he takes a "turn", he overwrites the previous information.

Change to:

while( $row = mysqli_fetch_assoc($resultado))

        $novo['codigo_produto'] = $row['codigo_produto'];
        $novo['id'] = $row['id'];
        $novo['codigo_tipo'] = $row['codigo_tipo'];
        $novo['descricao'] = $row['descricao'];

        array_push($valores, $novo);
    }

    print_r($valores);

And run for the hug!

  • Thank you, I’m close now with your help, I’ll update the functionx.php file code for you to check. Because within Inspect => Network tab I have the data return in array but, are not brought on screen to the user

1


You must remove the line

print_r($valores);

of the archive function.php and then treat the return.

var html = ""; 
$.getJSON('functionx.php',{ 
    descricao: $( this ).val() 
},function( json ){
    for (var i = 0; i < json.length; i++) {
        html += '<tr>';
            html += '<td><input type="hidden" name="id[]" value="'+json[i].codigo_produto+'"></td>';
            html += '<td><input type="text" name="codigo_tipo[]" value="'+json[i].codigo_tipo+'" /></td>';
            html += '<td><input type="text" name="descricao[]" value="'+json[i].descricao+'" /></td>';
        html += '</tr>';
    }
    $("table tbody").html(html);
});

You can see in the jsbin

  • I changed the code this way and the return of Json only goes to the Network tab and nothing to complete on the screen, that strange, and in jsbin is just what I want. I’ll edit to show how the Function turned out

  • 1

    Removes the line print_r($valores); of the archive function.php

  • ok, I made the editing with the changed Javascript and the file Function.php also

  • 1

    It still didn’t work ?

  • It worked, only it creates the lines below the table posted a print, when this empty comes with 5 blank lines as in your example Jsbin, but when the function is triggered/executed. This is what I posted in the print

  • 1

    In the Jsbin it is returning with the values of the json not this emptiness

  • I guess I didn’t know how to express myself, the table before I type anything it already comes blank with 5 lines, and then when I run the function, instead of it filling the blank fields it creates 5 filled fields more below the 5 blank lines

  • See now, if it’s right.

  • Now it does not create another 5 fields but, is bringing only the last record in all lines

  • Well, I came back like before, but now I’ve changed $("table tbody").append(html); for $("table tbody").html(html);

  • Now it’s worked out, man, thank you very much, I’ve been waiting all day for this. I am beginner in Javascript and PHP, sorry for encomodar so much, I will mark as the best answer without doubts

Show 6 more comments

Browser other questions tagged

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