peke_peke peke_peke - 5 months ago 13
JSON Question

Load JSON with AJAX to be used in another function

I've got two functions, one is called as soon as a button is triggered, the other one when the "process" triggered by the button is finished.
I would like to to load the JSON data from the AJAX request in the

calculatePrize()
function to reduce loading time at the end of function
Finish()


function calculatePrize() {
// ...some code goes here
// I would like to load the AJAX data already here and just parse it in the "finish Function"
}

function Finish() {
// retrieve win
$.getJSON("/generate").done(function(data){
// console.log(data.state)
// set the win amount
amount_field.append( document.createTextNode(data.win_amount));
});
}


How to do so in the best way?

Answer

You can just call the calculatePrize function from the Ajax Done - and pass the data as parameter

function calculatePrize(responsData) {
     console.log(responseData);
}

function Finish() {
    // retrieve win
    $.getJSON("/generate").done(function(data){

       // Call the function - pass the data as parameter
       calculatePrize(data);

    });
}

OR

store the data in a global variable and access in the calculatePrize function

    var responseData = null;

    function calculatePrize() {
         console.log(responseData);
    }

    function Finish() {
        // retrieve win
        $.getJSON("/generate").done(function(data){

           responseData = data;

           // Call the function 
           calculatePrize();

        });
    }
Comments