Assign $.ajax received value to variable

Asked

Viewed 3,043 times

2

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

Follows code 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 take these figures(data) received at .done and assign them to global variables, because I have more functions that need these values to be summed.

EDIT: I tried to do using window.variavel_global in that passage:

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

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

console.log( window.vg);

It doesn’t work and returns Undefined on the console.

3 answers

3


You can use a global variable but you have to take into account that that variable only gets its value afterward ajax to be finished. That is to say it gets status undefined until you receive value within the .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 within of .done(). And so in practice you don’t even need the global variable...

It would be something like that:

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

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;
});

0

Declare the variable like this:

window.VariavelGlobal

As you know, Javascript has two types of variables, global and local. Local variables are declared within the scope of a function, whereas global variables have their value accessible anywhere in the program, with this comes 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 variable name:

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

Example 2 (does not work, variavel_local is local and can only be accessed from within the function):

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

  • Hi, I tried to use with window and it still didn’t work. The variable comes empty, I checked the console.

  • It was supposed to work. I added an example in the code.

  • It didn’t work anyway :( I edited my question.

Browser other questions tagged

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