Lisa
Lisa

Reputation: 3

How to check what a function returned in JavaScript?

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?

Upvotes: 0

Views: 130

Answers (2)

nagisa
nagisa

Reputation: 720

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.

Upvotes: 2

SLaks
SLaks

Reputation: 887797

Your code is completely wrong.

You should just check whether result.result is true.

Upvotes: 3

Related Questions