Matt Herbstritt
Matt Herbstritt

Reputation: 4862

How to put getJSON values into a variable

I'm trying to understand jQuery's getJson(). I want to put the array that it returns into a variable put I don't know how. I get undefined when I click the start button in this code. I know that everything in the PHP file works so I don't think the propblem is there.

function getGameData(){
var difLevel = $("input[@name=difLevel]:checked").val();
var gameData = (function(){
    var json = null;
    $.getJSON('/Spelling4/core/proof_Test_JSON_process4.php',{difNo : difLevel},function(data){
        json = data;
    });
    return json;
});

return gameData;

}
$('#startButton').click(function(e) {
    var gameData = getGameData();
    e.preventDefault();
alert(gameData[1]);
});

Upvotes: 0

Views: 378

Answers (3)

Ram
Ram

Reputation: 144659

Ajax is asynchronous, when you call your function and if the ajax request is not completed your function returns null you should use deferred object. Note that your attribute selector is wrong you should remove the @.

var difLevel = $("input[name=difLevel]:checked").val();

Upvotes: 1

lhk
lhk

Reputation: 30016

I think you're storing a function in gamedata. You should be able to access the values with gameData()

Upvotes: 0

sarge
sarge

Reputation: 23

The JSON return data will end up in the json variable you specified. However, the JSON query is async so the response hasn't been returned when the getGameData() function is completed.

You need to use the JSON data within $.getJSON(...) instead of returning it.

Upvotes: 1

Related Questions