12

I'm sending some data in an Ajax call. One of the values is a boolean set to FALSE. It is always evaluated as TRUE in the PHP script called by the Ajax. Any ideas?

$.ajax({
    type: "POST",
    data: {photo_id: photo_id, 
           vote: 1, 
           undo_vote: false},   // This is the important boolean!
    url: "../../build/ajaxes/vote.php",
    success: function(data){
        console.log(data);
    }
}); 

In vote.php, the script that is called in the above Ajax, I check the boolean value:

if ($_POST['undo_vote'] == true) {
    Photo::undo_vote($_POST['photo_id']);
} else {
    Photo::vote($_POST['photo_id'], $_POST['vote']);
}

But the $_POST['undo_vote'] == true condition is ALWAYS met.

5

3 Answers 3

15

A post is just text, and text will evaluate as true in php. A quick fix would be to send a zero instead of false. You could also put quotes around your true in PHP.

if ($_POST['undo_vote'] == "true") {
    Photo::undo_vote($_POST['photo_id']);
} else {
    Photo::vote($_POST['photo_id'], $_POST['vote']);
}

Then you can pass in true/false text. If that's what you prefer.

4
  • Is it bad practice to send booleans as 0 or 1? Should I be doing some JSON encoding, or something else to make the type stronger?
    – Don P
    Feb 5, 2013 at 21:03
  • Your answer is correct and works by the way, just need 8 minutes to accept :)
    – Don P
    Feb 5, 2013 at 21:03
  • @DonnyP It's really a matter of taste. Most programmers know how 1 and 0 work for true/false, but depending upon where this is being used it may be clearer to use JSON.
    – Jeff Davis
    Feb 5, 2013 at 21:06
  • The traditional (pre-JSON, pre-REST) approach would be to include undo_vote: 1 for true and to exclude undo_vote altogether for false. Then, server-side booleanize $_POST['undo_vote'] depending on whether it's present or not (and optionally interpret '0' and 'false' as false). For something simple like this I might still use that approach today. Feb 5, 2013 at 21:29
5

You can use JSON.stringify() to send request data:

data : JSON.stringify(json)

and decode it on server:

$data = json_decode($_POST);

2

You can use 0 and 1 for undo_vote and type cast it in php:

JS side:

undo_vote: 0 // false

Server side:

$undovote = (bool) $_POST['undo_vote']; // now you have Boolean true / false

if($undovote) {
    // True, do something 
} else {
   // False, do something else 
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.