I have a method that sends AJAX request and returns a result that indicates a JSON string of Tokens records, I'm trying to get this result and assign it to a global variable called tokens and then reuse this global variable in other functions.
I'm assigning the result to that variable and log it to the console as follows:
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);
}
});
}
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 null.
For example I want to use it in the following jQuery code but it shows that the variable is null:
$("#example").DataTable({
"columns": getTokens(),
"data": tokens
});
Just to clarify that both variable and function are being defined inside:
$(document).ready(function () {//function and var}
Any suggestions please?