4

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?

3 Answers 3

6

Make sure the AJAX callback has finished before using the variables globally

Most of the time problems arise when you try to get a value via AJAX and then try to use that value outside the whole $.ajax() construct. The reason is that responses from async calls can only be accessed safely inside their success or complete callbacks - there is no guarantee the value will be populated before either of those callbacks complete. To work around this, you can either move all following code to be called from inside the AJAX callback, or wait for your global vars to be set by the callback.

Using the callback to continue running your script

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);

            EverythingElseYouWantToRun();
        }
    });
}

function EverythingElseYouWantToRun() {

    // you can do whatever you want with the response here

    $("#example").DataTable({
        "columns": getTokens(),
        "data": tokens
    });
}

Await the variable with your consuming script

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);
        }
    });
}

function RunWhenVariableIsPopulated(variable, callback, timeout) {

    if (variable === null) {

        setTimeout(function() {

            RunWhenVariableIsPopulated(variable, callback, timeout);
        }, timeout);

    } else {

        callback(variable);
    }
}

Then later you can call:

RunWhenVariableIsPopulated(tokens, function() {
    $("#example").DataTable({
        "columns": getTokens(),
        "data": tokens
    });
}, 400 /* or whatever your average round-trip time is*/);

Beware: this can cause the browser to hang noticeably if your AJAX response time is really long, and effectively turns an async call into a synchronous one. Hope this helps with your current situation!

Sign up to request clarification or add additional context in comments.

1 Comment

Great!, despite that the second methodology didn't work for me as calling the method RunWhenVariableIsPopulated stayed long time awaiting the variable to be set but it never done. But the first solution worked perfectly. I will consider this question as the answer because you provided a full answer by which you identified the concept of the issue and then provided a best solution, thanks dear again!
2
function getData(){
return $.ajax({
            type: "POST",
            url: "NewToken.aspx/PopulateAllTokens",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            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);
            }
        }).responseText;
}

var res = getData();

Above code will store the response in the variable and after that you can parse it and modify as you need. I am not sure, but It may help you

1 Comment

I had used it with get request and it worked smoothly.
0

use $.parseJSON() Method

$(document).ready() is doesn't matter, only thing is functions calls flow, you can declare the function outside also and call it accordingly, and also its good to check the variable null or not like

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 = $.parseJSON(result.d);
                    console.log(tokens);
                    populateTokensToTable(tokens);
                }
            });
        }

    if(tokens)
       console.log(tokens);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.