Frage

I'm newbie and have to following question:

i declared a global variable and alter the value within a function. But outside the value is still the old.

var allowDrag = 'false';

$.get('/cakeorga2/ajax/is_admin/', function (data) {
    allowDrag = data;
    console.log ('allowDrag in function : '+allowDrag);
});

console.log ('outside of the function : '+ allowDrag);

the console log was:

outside of the function : false
allowDrag in function : true

Any suggestions?

War es hilfreich?

Lösung

$.get is a shorthand method of $.ajax:

Perform an asynchronous HTTP (Ajax) request.

An ajax call is usually async so the main console.log will be fired before the $.get execution is completed (as you can see in the console order) and in that moment the allowDrag value is still false.

Andere Tipps

You were trapped. Global variables behave exactly as you expected. The reason it does not have the new value in your second console.log is a different one: By the time you execute the console.log, the ajax call issued with $.get has not been answered yet. If you need to use it like that you must make the call synchronous by using the async: false option.

Use deferred.then() to call the second console.log() only after the value has been updated (ajax GET has been successful)

$.get('/cakeorga2/ajax/is_admin/', function (data) {
  allowDrag = data;
  console.log ('allowDrag in function : '+allowDrag);
}).then( function(){
     console.log ('outside of the function : '+ allowDrag);
   }
);

http://api.jquery.com/deferred.then/

This happens because your ajax call is asynchronous. Asynchronous (in your use case) means your outside of the function console.log will execute before your ajax call returns.

Do it synchronous with $.ajax()

var allowDrag = 'false';

allowDrag  = $.ajax(
              {
               url:'/cakeorga2/ajax/is_admin/',
               async:false
              }).responseText;

console.log ('outside of the function : '+ allowDrag);

Well that might very well be because the console.log outside the function gets called before the one inside the function since you have to call the function yourself and the code around it gets "played" automatically. But since I'm not familiar with Ajax/jQuery I could be wrong.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top