0

Why is x undefined at line 11 when it is defined in line 9?

<script>
  var x;
  $.ajax({
    dataType: "json",
    url: myurl,
    success: function(data){
      console.log(data);
      x = data;
      document.write(x);
    }
  });
  document.write(x);
</script>
Shikhar
  • 357
  • 1
  • 3
  • 12

4 Answers4

5

Because you have asynchronous behavior here. The flow of your program is actually like this:

1- You declare x

2- You make an ajax request

3- You write x into the document (at this point, x has no value)

4- The ajax request gets a response and you set x's value to that response and write it on the document.

Your problem is not a matter of scope, it's a matter of timing.

Deleteman
  • 8,500
  • 6
  • 25
  • 39
1

That is because line 11 gets executed before the Ajax(Asynchronous) callback function success executes and set the value at line 8.

You may do this instead.

function MakeAjaxCall(callback)
{
  $.ajax({
    dataType: "json",
    url: myurl,
    success: function(data){
      console.log(data);
      callback(data);

    }
  });
}
function wantToCallAjaxAndUseResult()
{

    MakeAjaxCall(function(x){console.log(x)});
}
PSL
  • 123,204
  • 21
  • 253
  • 243
1

This has more to do with AJAX being asynchronous, rather than variable scope. Control immediately proceeds to line 11 where x is not defined. However, line 8 will be executed at some indeterminate point in the future (i.e., after the request is finished and the success callback is called and executed), after line 11 has executed.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
0

Ajax runs asynchronously. JavaScript makes a request and continues executing other code while waiting for the request to complete. This means that you can't depend on when the request will complete or even if it will complete. Thus all work that depends on the result of an ajax call must be done in the ajax callback. You simply can't rely on anything that happens inside of the ajax callback having an effect on anything outside of the callback at any time.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405