0

I have been playing with JSON/PHP/JS today and I am having problems..

My PHP works fine which gets a row of data from my SQL table then encodes as JSON. My JS/Jquery file loads the data from the PHP file fine using $.getJSON.

However, when i try and use the data later in the page like so: gender = user['player'].gender, I get user.player is undefined.

This is my code that is relevant:

function getUserInfo() {
    var url = "./php/getUserInfo.php";
    $.getJSON(url, function(data) {
        $.each(data.members, function(i, dat) {

            user['player'] = {
                gender: dat.gender,
                fname: dat.first_name,
                lname: dat.last_name,
                username: dat.username,
            };
        });
    });
}

user = {};
getUserInfo();

//Displays an object, which has the correct information I want.
console.log(user);
var gender = user['player'].gender;
console.log(gender);​

the last line of code gives me the error that user.playe is not defined. but it should display male Help would be helpful, I have tried many things to fix this but cant seem to do so.

1 Answer 1

4

$.getJSON is Asynchronous.

As soon as the request is sent , it goes to the next line and does not wait for the request to be completed.

So when you try to access the variable , it is still not available..

Try putting that piece of code after the $.each and it should work.

Sign up to request clarification or add additional context in comments.

5 Comments

how would i go about fixing this then.
well the returned data is only one rows worth, would removing the .each loop help and I just add the data to the first element.
To check which actually works .. Try putting two console.log statements , one inside the callback , and one outside.. Check what happens
console logs female in the callback but undefined when out of the function.
Which is called first , the undefined is logged first ... SO basically you need to move that piece of code inside the callback

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.