-2

How can I access inner_variable after it is getting defined by the ajax call?

PS: I can't change anything in the ajax call success callback. I tried to use setTimeout but it's not efficient enough.

jQuery(document).ready(function(){

   inner_variable = inner_variable + 1;


   jQuery.ajax({
         //code

   }).done(function(response){
     var inner_varaiable  = response;
   });


});
Waseem Senjer
  • 1,026
  • 3
  • 14
  • 25

3 Answers3

0

You need to use a callback function like below, you then use response by passing it through to the callback.

function myAjaxFunction (myCallback) {
    jQuery.ajax({
         //code

    }).done(function(response){
         myCallback(response);
   });   
}

myAjaxFunction(function (response) {
    console.log(response);
    // Then you can use response.
});

Because AJAX is asynchronous you can't do it like you wanted to.

Script47
  • 14,230
  • 4
  • 45
  • 66
0

If you can't change anything in the success callback, you could hook onto the ajaxComplete callback and put your setTimeout there.

$( document ).ajaxComplete(function() {
    // setTimeout or setInterval after a short delay to check inner_variable till it's defined 
});
potatopeelings
  • 40,709
  • 7
  • 95
  • 119
0

You have to take a look about scopes. I mean if you do :

   var myvalue; /*value undefined this scope is private */function test (){myvalue = 'foo'/*
This will overwrite myvalue outher context inside function myvalue produces foo */} //myvalue out the function is foo

When you declare var the context is private to the scope if you declare without var means the global scope and you can overwrite Hope you help

Joaquin Javi
  • 880
  • 7
  • 12