Assign value received from $ .ajax to the variable

2

It is possible to associate a value received with $.ajax with a global variable, because from these values, I need to add them and show them in another table. I have tried it however it always interprets with local variable, losing its value at the end of the function.

JS :

function buildTableNI(){ 

   $('#tb_ni').empty();
    $.ajax({
       type:'GET',
       crossDomain:true,
       url:'http://www.minhaurl.com.br/api/meuphp.php?callbackpni=?',
       dataType:'jsonp',
       data: {currency: $('#cur').val()},
       beforeSend: function(){
           $('#loading').css("display","block");
           $('table[name=tb_ni]').css("opacity","0.01"); 
       }    

    }).done(function(data){
            console.log(data);
           $('#loading').css("display","none");
           $('table[name=tb_ni]').css("opacity","1");

           $('#tb_ni').append('<tr> <td class="column_st">'+'Active'+
                                '</td><td class="column_qtd">'+data.ni_qtdA+
                                '</td><td id="" class="a">'+data.ni_active+
                                '</td><td>'+data.ni_p_active+'</td></tr>');
// quero pegar esses valores (data.ni_active,
//data.ni_p_active,etc e colocar seu valor em uma varivel global.)

           a = $('#ac3').append(parseInt(data.ni_qtdA));


           $('#tb_ni').append('<tr> <td class="column_st">'+'Inactive'+
                                '</td><td class="column_qtd">'+data.ni_qtdI+
                                '</td><td id="a3" class="i">'+data.ni_inactive+
                                '</td><td>'+data.ni_p_inactive+'</td></tr>');

           $('#tb_ni').append('<tr> <td class="column_st">'+'Won'+
                                '</td><td class="column_qtd">'+data.ni_qtdW+
                                '</td><td class="w">'+data.ni_won+
                                '</td><td>'+data.ni_p_won+'</td></tr>');

           $('#tb_ni').append('<tr> <td class="column_st">'+'Budget'+
                                '</td><td class="column_qtd">'+data.ni_qtdB+
                                '</td><td class="b">'+data.ni_budget+
                                '</td><td>'+data.ni_p_budget+'</td></tr>');

           $('#tb_ni').append('<tr> <td class="column_st">'+'Coming'+
                                '</td><td class="column_qtd">'+data.ni_qtdC+
                                '</td><td  class="b">'+data.ni_coming+
                                '</td><td>'+data.ni_p_coming+'</td></tr>');

           $('#tb_ni').append('<tr> <td class="column_st">'+'In Process'+
                                '</td><td class="column_qtd">'+data.ni_qtdP+
                                '</td><td class="p">'+data.ni_process+      
                                '</td><td>'+data.ni_p_process+'</td></tr>');

           $('#tb_ni').append('<tr> <td class="column_st">'+'N/I'+
                                '</td><td class="column_qtd">'+data.ni_qtdNI+
                                '</td><td class="ni">'+data.ni_ni+
                                '</td><td>'+data.ni_p_ni+'</td></tr>');

           $('#tb_ni').append('<tr class="head_table"> <td>'+'Total'+
                                '</td><td class="column_qtd">'+data.ni_qtd_total+
                                '</td><td  class="total">'+data.ni_total+
                                '</td><td>'+data.ni_p_total+'</td></tr>');

           $('#tb_ni').append('<tr> <td class="column_st">'+'Replaced'+
                                '</td><td class="column_qtd">'+data.ni_qtdR+
                                '</td><td  class="r">'+data.ni_replaced+
                                '</td><td>'+' - '+'</td></tr>');




    })
     .fail(function(data, textStatus, errorThrown){
        alert("Erro na operação.");
        console.log(data);
        console.log(textStatus);
        console.log(errorThrown);
    });

   return false; 
}

In short, I need to get these values ( data ) received in .done and assign them to global variables, as I have more functions that need these values to be summed.

EDIT: I tried to use window.variavel_global in this section:

}).done(function(data){
        window.vg = data.ni_active;
            console.log("variavel global:"+(vg));

Even shows in the console, but when I check the console of this variable outside of this function, like this:

console.log( window.vg);

It does not work and returns undefined on the console.

    
asked by anonymous 24.05.2016 / 04:18

3 answers

2

You can use a global variable but you have to take into account that this variable only gets its value after of ajax has ended. In other words, it gets a undefined state until it receives value inside .done() because ajax can take several seconds to complete. This is asynchronous, and the solution is to call the function that needs the variable with the ajax data inside of .done() . And so, in practice you do not even need the global variable ...

It would look something like this:

}).done(function(data){
        console.log(data);
        minha_funcao_que_precisa_da_resposta_do_ajax(data); // e aqui passas os dados que precisavas
    
24.05.2016 / 10:33
0

Declare the variable like this:

window.VariavelGlobal

As you know, JavaScript has two types of variables, global and local variables. Local variables are declared within the scope of a function, since the global variables have their value accessible in any part of the program, so there is a problem: their global variables can be overwritten by basically any other variable and by any object of window .

Example 1 (works, variavel_global is global and can be accessed from outside the function). Another approach is to remove any prefix var or window. , leaving only the name of the variable:

$(function(){
    function exemplo( data ){
        //poderia ser somente-> variavel_global = data;
        window.variavel_global = data;
    }
    
    exemplo('Valor de [data]');
    
    console.log(variavel_global);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Example2(notworking,variavel_localislocalandcanonlybeaccessedfromwithinthefunction):

$(function(){
    function exemplo( data ){
        var variavel_local = data;
    }
    
    exemplo('Valor de [data]');
    
    console.log(variavel_local);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    
24.05.2016 / 04:44
0

or you can use a callbak:

var myvar = null;

function buildTableNI(callback){ 

   $('#tb_ni').empty();
    $.ajax({
       type:'GET',
       crossDomain:true,
       url:'http://www.minhaurl.com.br/api/meuphp.php?callbackpni=?',
       dataType:'jsonp',
       data: {currency: $('#cur').val()},
       beforeSend: function(){
           $('#loading').css("display","block");
           $('table[name=tb_ni]').css("opacity","0.01");
       }

    }).done(function(data){
           //código de início de done()
          var retorno = {
            ni_active: data.ni_active,
            ni_p_active : data.ni_p_active
          }
          
          //chamada callback
          callback(retorno)
          
    //o resto de código vai aqui


    })
     .fail(function(data, textStatus, errorThrown){
        //função fail
    });

   return false;
}

buildTableNI(function(data){
    myvar = data;
});
    
24.05.2016 / 20:01