title: Assign Ajax result to global variable in Javascript
body: <p>I have a method that sends <code>AJAX</code> request and returns a result that indicates a <code>JSON string</code> of Tokens records, I'm trying to get this result and assign it to a global variable called <code>tokens</code> and then reuse this global variable in other functions.</p>
  
  <p>I'm assigning the result to that variable and log it to the console as follows:</p>
  
  <pre><code>var tokens = null;
  
  
  function PopulateAllTokens() {
              $.ajax({
                  type: "POST",
                  url: "NewToken.aspx/PopulateAllTokens",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  error: function (XMLHttpRequest, textStatus, errorThrown) {
                      alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                  },
                  success: function (result) {
                      tokens = JSON.parse(result.d);
                      console.log(tokens);
                      populateTokensToTable(tokens);
                  }
              });
          }
  </code></pre>
  
  <p>The issue is that, when I assign the result to the variable and then log it to the console it shows the result successfully, but when I want to reuse it later in other functions it shows that the variable is still <code>null</code>.</p>
  
  <p>For example I want to use it in the following <code>jQuery</code> code but it shows that the variable is null:</p>
  
  <pre><code>$("#example").DataTable({
          "columns": getTokens(),
          "data": tokens
      });
  </code></pre>
  
  <p>Just to clarify that both variable and function are being defined inside: </p>
  
  <p><code>$(document).ready(function () {//function and var}</code></p>
  
  <p>Any suggestions please?</p>