0

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

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you say I need to remove the @? It's been working fine with it so far. Thanks for your response.
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.