0
$("#login").click(function(){

    $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){
        console.log(data);  //get whatever i have in login box and sends to my handler returning the json array
    });
        template = $("#hidebody");
    if(!data['error']){
        template.show();
        //$("#greeting")
    }
    else
    {
        template.hide();
    }
    return false;
});

So far the top part works, which means whatever name i type in username box it is send to my handler login.php, when i do a console.log, and so on console i get my json array back from my database which works, now I need some help writing a if and else statment where the comment box appears after the person logs in, which hides the userbox, and password box, and as a greet statment displaying the person name from the database.

2 Answers 2

1

Since Javascript is an asynchronous language, there's no guarantee that the data from $.getJSON will be available unless passed through a callback or returned in a promise. In my below example, I pulled the function definitions out into their own variables instead of defining them inline, to help illustrate the flow of the program.

// Define a login method which grabs data and passes it to a callback
var login = function (username, callback) {
    $.getJSON("handlers/Login.php?name=" + username, callback);
};

// Define a method which handles the response returned from the login URL
var handleResponse = function (data) {
    console.log(data);

    var template = $('#hidebody');

    if(!data['error']) {
        template.show();
    } else {
        template.hide();
    }
};

// Register the onClick event which calls the login method
$("#login").click(login($('#username').val(), handleResponse));
Sign up to request clarification or add additional context in comments.

Comments

0

Since getJSON is going to run asynchronously you need to add your data handling functionality into that callback where you are currently logging the data.

Something like this:

$("#login").click(function(){

    $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){
        console.log(data);  //get whatever i have in login box and sends to my handler returning the json array
            template = $("#hidebody");
            // Any other logic for parsing / handling of returned JSON
            if(!data['error']){
                template.show();
                //$("#greeting")
            }
            else
            {
                template.hide();
            }
    });

    return false;
});

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.