0

I am using a JSON function that checks to see if a username is avaiable or has already been taken.

The function returns either this (if username is avaliable):

{"error":null,"jsonrpc":"2.0","id":1,"result":true}

or this if it isn't:

{"error":null,"jsonrpc":"2.0","id":1,"result":false}

so to perform an action based on the result I need to first check what the function returned. When I tried this:

                if (JSON.stringify(result) == '{"error":null,"jsonrpc":"2.0","id":1,"result":true}') {
                    avaliability.html('avaliabile');
                }
                else if (JSON.stringify(result) == '{"error":null,"jsonrpc":"2.0","id":1,"result":false}') {
                    avaliability.html('not avaliabile');
               }

it didn't work. Neither did this:

                    if (JSON.stringify(result).search('false') != -1) {
                        alert('not avaliabile');
                    }
                    else if (JSON.stringify(result).search('true') != -1) {
                        alert('avaliabile');
                    }

or this:

                    if (JSON.stringify(result) == false) {
                        alert('not avaliabile');
                    }
                    else if (JSON.stringify(result) == true) {
                        alert('avaliabile');
                    }

How to check if the JSON function returned true or false?

0

2 Answers 2

3

Your code is completely wrong.

You should just check whether result.result is true.

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

Comments

2

JSON.parse('{"error":null,"jsonrpc":"2.0","id":1,"result":false}').result returns false, and JSON.parse('{"error":null,"jsonrpc":"2.0","id":1,"result":true}').result returns true, so actual code should look like this:

if(JSON.parse(result).result == true){
    alert('Available')
}else{
    alert('Not available')
}

Of course, considering, that result is string. If it's already Object(parsed), then you should do as SLaks said.

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.