Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Ajax result to global variable in Javascript

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?

like image 457
Husain Alhamali Avatar asked Mar 11 '23 20:03

Husain Alhamali


2 Answers

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!

like image 189
ppajer Avatar answered Apr 02 '23 13:04

ppajer


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

like image 44
Rupesh babu Shrestha Avatar answered Apr 02 '23 14:04

Rupesh babu Shrestha