Reputation: 63577
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.
Upvotes: 12
Views: 37029
Reputation: 2648
An old question, but maybe this is useful for Javascript programmers:
I do not want to stringify everything, since I want numbers and booleans without quotes, strings with one pair of double quotes, and objects as they are in my request body.
JQuery ajax did not accept pure boolean values as data body, so I did:
if (jQuery.type(data) == 'boolean') {
data = JSON.stringify(data);
}
Works for me...
Upvotes: 0
Reputation: 31
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
}
Upvotes: 2
Reputation: 51
You can use JSON.stringify() to send request data:
data : JSON.stringify(json)
and decode it on server:
$data = json_decode($_POST)
;
Upvotes: 5
Reputation: 4797
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.
Upvotes: 15