• 5
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 187

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 187
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Send a boolean value in jQuery ajax data

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.

    • Have you tried if ($_POST['undo_vote'] == 'true') {? (I'd expect request parameters to be received as strings unless you pass a string of JSON and parse it server-side before testing the individual properties.)

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.

  • 14
Reply Report
      • 1
    • 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?
      • 2
    • @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.
    • 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.

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 
}
  • 0
Reply Report