Load jQuery does not capture data

0

Hello, I made a registration page, where I can consular source and recipient, working perfectly.

Now I'm doing the editing page. As I already have the source and destination cpf_cnpj, I need getJSON, query immediately showing the values.

When the page loads, the fields are populated:

$(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);


        });
    };

});

NowthiscodeshouldgetthevalueoftheStatusfield#estado2(Imageabove)togetJSON,butthisdoesnothappenwhenthepageloads.

$(document).ready(function(){executa3();$('.transportadora,.destino,.tabbable').on('loadclick',executa3);functionexecuta3(){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 an edit page, the state should move to getJSON once the page loads, but I can not, only when I execute the action of click , that works.

Viewing from the chrome inspector:

Nowifyouleaveinput#state2declaredinhtmlvalue="RJ" it works. It looks like execute3 () can not get the value entered by executa2 () in the input.

    
asked by anonymous 24.06.2015 / 21:45

1 answer

1

James , what's happening is probably that your executa3() is being called BEFORE your executa2() .

You have two options:

  • Use callback in executa2(callback) and then call it at the end of the field fill
  • You can also keep the loading order exactly like this: executa2() -> executa3() and disable the "asynchronous" option async: false in the ajax options.
  • "CALLBACK" OPTION

    $(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 ajax of executa2()

    ASYNC OPTION IN BOTH AJAX REQUIREMENTS

    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 does not run concurrently (causing the risk of one running before another)

        
    24.06.2015 / 22:47