0

I'm trying to use the jQuery.get() function get data from an url and set the retreived data to a variable outside this jQuery.get() function.

 var rating = 0;

 $.get( "/qwerty/res/film/rating?volgnummer=2", function( data ) {  // the url returns 99
     rating = data; 
      $( ".content" )
        .append(data); // returns 99 (as expected)
    }, "json" );

alert(rating); // returns 0 (99 expected)

The .append(data) returns the right result but when I alert the rating variable outside the get function it returns 0(which should be 99)

Why isn't the rating variable set to 99(from data)?

Johan
  • 69
  • 2
  • 10

2 Answers2

0

Because ajax is asynchronous. Your alert runs before the ajax callback that sets rating.


(CW because this is such a duplicate!)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

It is happening because alert is called before $.get finished execution.

try this:

var rating = 0;
get_json(function(){
    alert(rating);
});
function get_json(callback){
    $.get( "/qwerty/res/film/rating?volgnummer=2", function( data ) {  // the url returns 99
        rating = data; 
        $( ".content" ).append(data); // returns 99 (as expected)
    }, "json" );
}
codingrose
  • 15,563
  • 11
  • 39
  • 58