Send boolean in jQuery ajax data

I am sending some data to an Ajax call. One of the values ​​is a logical set equal to FALSE. It is always evaluated as TRUE in the PHP script called by 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 condition $_POST['undo_vote'] == true occurs ALWAYS.

+7
source share
3 answers

A message is just text, and the text will be evaluated as true in php. A quick fix would be to send zero instead of false. You can also put quotes around your true one 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 true / false text. If that is what you prefer.

+12
source

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

data : JSON.stringify(json)

and decode it on the server:

$data = json_decode($_POST) ;

0
source

You can use 0 and 1 for undo_vote and type cast 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 } 
0
source

All Articles