How to perform sub-discharge with auto-fill

Asked

Viewed 115 times

0

Code that performed the consultation:

$parametro = (isset($_GET['parametro'])) ? $_GET['parametro'] : '';

if($acao == 'consulta'):
$sql = "SELECT codigo,preco FROM produtos ";
$sql .= "WHERE descricao LIKE ? LIMIT 1";

try{
    $query_select = $conecta->prepare($sql);        
    $query_select->bindValue(1, '%'.$parametro);
    $query_select->execute();
    $dados = $query_select->fetchAll(PDO::FETCH_OBJ);
}catch (PDOexception $error_select){
    echo 'Erro ao selecionar: '.$error_select->getMessage();
}

$json = json_encode($dados);
echo $json;
endif;

Load query data in the "Code" and "Price" fields":

function carregarDados(){
    var busca = $('#busca').val();
    if(busca != "" && busca.length >= 2){
        $.ajax({
            url: "consulta.php",
            dataType: "json",   
            data: {
                acao: 'consulta',
                parametro: $('#busca').val()
            },
            success: function( data ) {
               $('#codigo').val(data[0].codigo);
               $('#preco').val(data[0].preco);
            }
        });
    }
}

and function to trigger autocomplete

$( "#busca" ).autocomplete({
    minLength: 2,
    source: function( request, response ) {
        $.ajax({
            url: "consulta.php",
            dataType: "json",
            data: {
                acao: 'autocomplete',
                parametro: $('#busca').val()
            },
            success: function(data) {
               response(data);
            }
        });
    },
    focus: function( event, ui ) {
        $("#busca").val( ui.item.descricao );
        carregarDados();
        return false;
    },
    select: function( event, ui ) {
        $("#busca").val( ui.item.descricao );
        return false;
    }
})

.autocomplete( "instance" )._renderItem = function(ul, item) {
    return $( "<li>" ).append( "<strong>Código: </strong>" + item.codigo
    + "&nbsp; | &nbsp; <strong>Descrição: </strong>" + item.descricao
    + "<br>" ).appendTo(ul);
};

The query is performed based on the description of the search field and the return is displayed in the fields "Code" and "Price", however when there are two products with the same description and different codes the fields mentioned are not updated.

Illustration:

inserir a descrição da imagem aqui

Code, explanation and execution found in links:

https://www.youtube.com/watch?v=PPROnjv1fhI

http://www.devwilliam.com.br/php/autocomplete-com-jquery-ui-php-mysql

No answers

Browser other questions tagged

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