get mysql data using javascript and ajax

3

I'm developing a web app (if interested, follow link) and it was going alright , until I get to the part below:

TheNCMfieldisainputtagwithadisabledattribute.TheinformationinsideitcomesfromanautocompletethatIused,usingAJAX,adatabasesearch.phpfiletoreturnthedatainjson.

THEPROBLEMS

I'musingthefollowingphpcodetoaccessthedatabaseandreturnthedata(ps:thereisalreadyatableinthesamedatabaseforthefirstautocomplete)

<?php//Dadosdaconexãocomobancodedadosdefine('SERVER','xxx');define('DBNAME','cl36-rickpara');define('USER','xxx');define('PASSWORD','xxx');//RecebeosparâmetrosenviadosviaGET$acao=(isset($_GET['acao']))?$_GET['acao']:'';$parametro=(isset($_GET['parametro']))?$_GET['parametro']:'';//Configuraumaconexãocomobancodedados$opcoes=array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SETNAMESUTF8');$conexao=newPDO("mysql:host=".SERVER."; dbname=".DBNAME, USER, PASSWORD, $opcoes);

            // Verifica se foi solicitado uma consulta para o autocomplete
            if($acao == 'autocomplete'):
                $where = (!empty($parametro)) ? 'WHERE codigo_item LIKE ?' : '';
                $sql = "SELECT codigo_item, descricao_item, aliq_ipi, ncm FROM base_prod " . $where;



            $stm = $conexao->prepare($sql);
            $stm->bindValue(1, $parametro.'%');
            $stm->execute();
            $dados = $stm->fetchAll(PDO::FETCH_OBJ);

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

            // Verifica se foi solicitado uma consulta para preencher os campos do formulário
                if($acao == 'consulta'):
                    $sql = "SELECT codigo_item, descricao_item, aliq_ipi, ncm   FROM base_prod ";
                $sql .= "WHERE codigo_item LIKE ? LIMIT 1";

                $stm = $conexao->prepare($sql);
                $stm->bindValue(1, $parametro.'%');
                $stm->execute();
                $dados = $stm->fetchAll(PDO::FETCH_OBJ);

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

            // Verifica se foi solicitado uma consulta para preencher o mva
                if($acao == 'consulta'):
                $sqlz = "SELECT ncm, rs, sc, sc_simples, rj, mg, mt, ap FROM nmcMVA " . $where; 
                $sqlz .= "WHERE ncm LIKE ? LIMIT 1";

                $stm = $conexao->prepare($sqlz);
                $stm->bindValue(1, $parametro.'%');
                $stm->execute();
                $dados = $stm->fetchAll(PDO::FETCH_OBJ);

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

And the following javascript (jquery) for AJAX query the data:

            $(function() {

                // Atribui evento e função para limpeza dos campos
                $('#busca').on('input', limpaCampos);

                // Dispara o Autocomplete a partir do segundo caracter
                $( "#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.codigo_item );
                        carregarDados();
                        return false;
                    },
                    select: function( event, ui ) {
              $("#codigoItem").val(ui.item.codigo_item);
              $("#descricao").val(ui.item.descricao_item);
              $("#aliqIPI").val(ui.item.aliq_ipi);
              $("#ncm").val( ui.item.ncm);
              return false;
            }
                })
                .autocomplete( "instance" )._renderItem = function( ul, item ) {
                    return $( "<li>" )
                    .append( item.codigo_item+ " — " + item.descricao_item )
                    .appendTo( ul );
                };

                // Função para carregar os dados da consulta nos respectivos campos
                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 ) {
                                $('#codigoItem').val(data[0].codigo_item);
                                $('#descricao').val(data[0].descricao_item);
                                $('#aliqIPI').val(data[0].aliq_ipi);
                                $('#ncm').val(data[0].ncm);
                            }
                        });
                    }
                }

               //Função para carregar os dados da consulta no campo MVA
                function carregarDados(){
                    var busca = $('#ncm').val();

                    if(busca = $('#ncm').val()){
                        $.ajax({
                            url: "consulta.php",
                            dataType: "json",   
                            data: {
                                acao: 'consulta',
                                parametro: $('#ncm').val()
                            },
                            success: function( data ) {
                                $('#mva').val(data[0].rs);
                            }
                        });
                    }
                }


                // Função para limpar os campos caso a busca esteja vazia

                function limpaCampos(){
                    var busca = $('#busca').val();
                    if(busca == ""){
                        $('#codigoItem').value('');
                        $('#busca').val('');
                        $('#descricao').val('')
                        $('#aliqIPI').val('');

                    }
                }
            });

The data submitted should appear in the corresponding html tags

					<p><span class="labelFake">NCM: </span><input type="text" id="ncm" disabled></p>
				<p><span class="labelFake">MVA: </span><input type="text" id="mva" disabled></p>

But according to the image, the MVA field is not being populated with the database information.

Could anyone help me?

    
asked by anonymous 14.01.2017 / 23:02

2 answers

0

Friend, your query in the database does not have the MVA field.

In your interface you also do not have a mva element. $('#mva') will always be null.

So I do not see how it works as you wish.

If I misunderstand, explain your problem better.

    
25.01.2017 / 23:56
0

When disabled, does not save. It tries in HTML to remove the disabled.

<p><span class="labelFake">MVA: </span><input type="text" id="mva"></p>

Copy and run, see if it worked. The solution is to put a disabled, and another to calculate from behind in php without the user see.

    
02.05.2018 / 13:29