get mysql data using javascript and ajax

Asked

Viewed 1,965 times

4

I’m developing a web app (case interest, follow link) and it was going all right until I got to the bottom:

inserir a descrição da imagem aqui

The field NCM is a tag input with a disabled attribute. The information within it comes from an auto complete I used, using the AJAX, a database a search.php file to return the data in json.

THE PROBLEMS

I am using the following php code to access the database and return the data (ps: there is already a table, in the same database, referring to the first autocomplete)

            <?php 
            // Dados da conexão com o banco de dados
            define('SERVER', 'xxx');
            define('DBNAME', 'cl36-rickpara');
            define('USER', 'xxx');
            define('PASSWORD', 'xxx');

            // Recebe os parâmetros enviados via GET
            $acao = (isset($_GET['acao'])) ? $_GET['acao'] : '';
            $parametro = (isset($_GET['parametro'])) ? $_GET['parametro'] : '';

            // Configura uma conexão com o banco de dados
            $opcoes = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
            $conexao = new PDO("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 to 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('');

                    }
                }
            });

Obituated data 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>

However, according to the image, the MVA field is not being filled in with the database information.

Could someone help me?

  • From a.log() console in the JSON that is returned and see if it is coming empty or filled in, so you can find out if the error is on the front or back.

  • I recommend you take the dataType: "json", jQuery and give an Alert in the date variable in Success. I think this could be a back end error if the PHP error display is active, possibly it is being returned along with the JSON object.

  • The code has 2 functions with the same name carregarDados. The second will rewrite the first.

2 answers

0

When it is "disabled", it does not store. Try removing disabled in HTML.

<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 behind in php without the user seeing.

0

Friend, in your query in the database you do not have the said MVA field.

In its interface also has no mva element. $('#mva') will always be null.

Therefore, I do not see how to function as you wish.

If I misunderstood, explain your problem better.

Browser other questions tagged

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