Subpar Web Dev
Subpar Web Dev

Reputation: 3260

How can I get a PHP function that handles an AJAX function to return a boolean?

So I've been testing and found out that if

session_start();
if ( $_POST['animal'] != $_SESSION['animal'] ) die(json_encode(false)); 

is run inside my PHP function to handle the AJAX call, then back in JavaScript land where I have

        success: function (correctCaptcha) {
            console.log("correctCaptcha is " + correctCaptcha); // test
            console.log("correctCaptcha's type is " + typeof (correctCaptcha)); // test
                if ( correctCaptcha )
                {

I'm seeing that correctCaptcha is the string "false" rather than the boolean value false. Consequently, the if block is entered and that's what's causing a bug. How can I get PHP to give me a boolean as the JSON it generates? Or what is a better solution?

Upvotes: 0

Views: 58

Answers (1)

VIDesignz
VIDesignz

Reputation: 4783

You can do

json_encode((bool)1); // which is true

Or

json_encode((bool)0); // which is false

Ideally though you would want to do something like this

$results = ["result" => false];
json_encode($results);

From the documents, this should retain the boolean, not convert to a string.

Then access the results in your javascript like this (as an object)

console.log(correctCaptcha.result);

Upvotes: 2

Related Questions