Jquery/Javascript Skipping lines?

Go To StackoverFlow.com

0

I'm trying to run a jQuery/Javascript function that searches an external JSON file, and returns true if the given variable is found as one of the usernames of the JSON.

This is what I have: (The given variable player is equal to a)

function loggedIn(player) {
    var result = false;
    var liurl = "liplay.json";
    $.getJSON(liurl, function (json) {
        $.each(json, function (key, value) {
            if (value.username == player) {
                alert();
                result = true;
            } else {}
        });
    });
    return result;
}

The External JSON file (liplay.json) is like this:

[{"username":"a"},{"username":"q"}]

For some reason, the code always returns false.

I tried running it one step at a time and I found out that for whatever reason, Chrome is running the first few lines of code until $.getJSON(liurl, function(json){, and then skipping until return result;. I can't tell why it's skipping the part where it runs the if/else statement. Any ideas on why this is happening and how to fix it?

2012-04-04 01:41
by user1311736
Don't return the result in loggedIn function, just do whatever you need in the success callback of getJSON. This is because it executes asynchronously - dan radu 2012-04-04 01:49
I believe once you get your JSON deserialized, you can simply check the array without looping through it:

return json[player] != undefined - Chris Gessler 2012-04-04 11:24



0

The $.getJSON call executes your function in a callback, so you can't return the result since it spins off the call and jumps to the return statement. You will have to refactor things in order to use a callback once the JSON call has finished loading

2012-04-04 01:52
by Andrew Burgess


0

$.getJSON is an asynchronous method - the function callback that you pass into it is what is executed once the asynchronous method has finished executing, but until then, the rest of the main function continues to execute, and inevitably returns false.

2012-04-04 01:57
by Scott Hamper