Load jQuery does not capture data

Asked

Viewed 96 times

0

Hello, I made a registration page, where I get consular origin and destinatario, working perfectly.

Now I’m doing the editing page. Since I already have the cpf_cnpj of origin and destination, I need getJSON, make the query immediately showing the values.

When the page is loaded, the fields are filled in:

$(document).ready(function(){
    executa2();
    $("#cpf_cnpj2").on('blur load',executa2);

    function executa2(){
       nome=$("#cpf_cnpj2").val();

        $.getJSON("cotacoesBuscaCliente.php", {cpf_cnpj:nome}, function(json){


            $("#cpf_cnpj2").val(json[0].cpf_cnpj);
            $("#isento2").val(json[0].isento);
            $("#suframa2").val(json[0].suframa);
            $("#rsocial2").val(json[0].rsocial);
            $("#nfantasia2").val(json[0].nfantasia);
            $("#ie2").val(json[0].ie);
            $("#im2").val(json[0].im);
            $("#cep2").val(json[0].cep);
            $("#rua2").val(json[0].rua);
            $("#num2").val(json[0].num);
            $("#comple2").val(json[0].comple);
            $("#bairro2").val(json[0].bairro);
            $("#cidade2").val(json[0].cidade);
            $("#estado2").val(json[0].estado);
            $("#pais2").val(json[0].pais);


        });
    };

});

inserir a descrição da imagem aqui

Now this code must take the value of the State field #estado2 (Image above) to go to getJSON, but this does not happen when the page is loaded.

$(document).ready(function(){
    executa3();
    $('.transportadora, .destino, .tabbable').on('load click', executa3);
    function executa3(){
       id       = $("input[type=radio][name='transportadora']:checked").val();
        estado  = $("#estado2").val();
        peso    = $("#maiorPeso").val();
        destino = $("input[type=radio][name='destino']:checked").val();


        $.getJSON("cotacoesBuscaTransportadora.php", {id_transportadora:id, estado:estado, peso:peso, destino:destino}, function(json){


            $("#estadoT").val(json[0].estadoT);
            $("#valorCap").val(json[0].valorT);
            $("#valorExcedCap").val(json[0].valorExced);
            $("#adValorem").val(json[0].valorAlorem);
            $("#prazoCap").val(json[0].prazo);

            var GETEstado = json[0].GETEstado;
            var ResulteZero = json[0].ResulteZero;

            //if (GETEstado == ""){
            //  $.gritter.add({
            //      title: 'Erro',
            //      text: 'Preencha os dados do destinatário',
            //      class_name: 'gritter-error'
            //  });
            //}

            if (ResulteZero == 0) {
                $.gritter.add({
                    title: 'Erro',
                    text: 'Essa transportadora não entrega no estado de destino ou destino não preenchido.',
                    class_name: 'gritter-error'
                });
            }

            if (json[0].valorAlorem == "") {
                $.gritter.add({
                    title: 'Erro',
                    text: 'Essa transportadora não faz entrega "Fluvial" ou não existe cadastro do mesmo.',
                    class_name: 'gritter-error'
                });
            };


        });
    };

});

As it is an editing page, the State should pass to the getJSON as soon as the page is loaded, but I cannot, only when I perform the action of click, that works.

Seeing by Chrome’s inspector:

inserir a descrição da imagem aqui

Now if you let input #state2 declared in html value="RJ" works. It seems that the execution3() cannot take the value entered by executa2() in the input.

  • Put the part of the form that has the #estado2

  • @Maiconcarraro O html?

  • Yes, but not everything, only that it’s relevant

  • <input name="estado2" id="estado2" type="text" class="form-control" value="" readonly />

  • Try taking readonly just to see. @Thiago

  • The executa3 is not being executed before the executa2?

  • I’ve tried without the readonly. The order is the same that I put up.

Show 2 more comments

1 answer

1


James, what’s probably going on is that your executa3() is being called BEFORE your executa2().

You have two options:

  1. Use a callback in executa2(callback) and then call you at the end of the fields fill
  2. You can also keep the loading order exactly like this: executa2() -> executa3() and disable the option "asynchronous" async: false in the options of ajax.

OPTION "CALLBACK"

$(document).ready(function(){

    function executa2(callback){
       nome=$("#cpf_cnpj2").val();

        $.getJSON("cotacoesBuscaCliente.php", {cpf_cnpj:nome}, function(json){


            $("#cpf_cnpj2").val(json[0].cpf_cnpj);
            $("#isento2").val(json[0].isento);

            // (...) restante do executa2()

            if (typeof callback != 'undefined')
                callback(); // aqui estamos executando executa3() que foi passado pelo parâmetro

        });
    };


    $("#cpf_cnpj2").on('blur load',

            executa2(function() // aqui estamos chamando executa2() para execução e ao mesmo tempo passando executa3() como parâmetro
            {
                $('.transportadora, .destino, .tabbable').on('load click', executa3);

                function executa3(){

                    id       = $("input[type=radio][name='transportadora']:checked").val();

                    // (...) restante do executa3()

                };
            });

    );

});

Obs.: You can also declare both functions and simply call executa2(executa3()), obviously keeping the callback call at the end of the ajax of the executa2()

ASYNC OPTION ON BOTH AJAX REQUESTS

Note async: false:

$.ajax({
  method: "POST",
  url: "some.php",
  async: false,
  data: { name: "John", location: "Boston" }
});

Explanation: with async: false, the ajax request follows a "queue" and is not executed in competition (causing the risk of one being executed before the other)

  • async: false is to be avoided...

  • That’s not the problem. I did a test, in the #state2 input I left declared value="RJ", then he carries it right. It seems that the execution3(); is not able to take the value that the executa2(); input.

  • Tried typing through the console $('#estado2').val() ?

  • Yes, from RJ, http://i.imgur.com/Uewoxjr.png

  • @James, tried to call console.log(estado) in executa3() right after he’s declared?

  • No, how should I?

  • It seems that the problem is in taking the value of input #stage 2

  • @Exact James, this is the problem. But remember that it is filled BEFORE by executa2(). So we need to know if by going through the ajax of executa3(), if its value is valid. You can enter console.log(estado) right under destino = $("input[type=radio][name='destino']:checked").val();

  • @I’m in the chat room

Show 5 more comments

Browser other questions tagged

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