Send a boolean value in jQuery ajax data
28,361
Solution 1
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.
Solution 2
You can use JSON.stringify() to send request data:
data : JSON.stringify(json)
and decode it on server:
$data = json_decode($_POST)
;
Solution 3
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
}
![Don P](https://i.stack.imgur.com/ufPVV.jpg?s=256&g=1)
Comments
-
Don P over 3 years
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. -
Don P over 11 yearsIs 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 over 11 yearsYour answer is correct and works by the way, just need 8 minutes to accept :)
-
Markus Schober over 11 years@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.
-
Beetroot-Beetroot over 11 yearsThe traditional (pre-JSON, pre-REST) approach would be to include
undo_vote: 1
for true and to excludeundo_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.