1

For some reason the newdata inside the get function is being lost when trying to use it outside the function. The alert shows 0, but when I put the alert in the get function it shows 80 (which is what it should be.) any ideas??

var newdata = 0;
//Get latest stat from file
$.get( "http://localhost/?stat=size", function( data ) {
   //Strip any letters from result (if any)
    newdata = data.replace(/\D/g,'');
   //alert( "Load was performed."+newdata );
});
alert( "Load was performed."+newdata );

Thanks

deejuk
  • 105
  • 7

1 Answers1

0

Your variable is not getting lost, jQuery get is a asynchronous request. Which means when you alert you have not got your data back yet so it will still return 0.

You could change your code to run synchronously which will solve your problem however you should be careful as it will prevent any more code executing until you get your response.

$.ajax({
         url:    'http://localhost/?stat=size', 

         success: function(data) {
                       newdata = data.replace(/\D/g,'');
                  },
         async:   false
    });     

However I would suggest just running what ever you need to do inside your get success, this means it will only run once you have retrieved your data and will not block any other execution.

var newdata = 0;
//Get latest stat from file
$.get( "http://localhost/?stat=size", function( data ) {
   //Strip any letters from result (if any)
    newdata = data.replace(/\D/g,'');
alert( "Load was performed."+newdata );
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
  • That will work fine, it doesn’t matter if it stops other code, its time based. (I updated the function(result) to function(data). Worked perfectly thanks for your help. – deejuk Feb 10 '14 at 11:32