boolean variables posted through AJAX being treated as strings in server side

前端 未结 4 1683
南方客
南方客 2020-12-03 00:41

Following is a part of an AJAX functionality to add classes and packs to session cart:-

The jquery part

function addClassToCart(item         


        
相关标签:
4条回答
  • 2020-12-03 01:18

    You aren't doing anything wrong per se, it's just that when it gets posted, it looks like this:

    operation=add_cart&isClass=true&itemId=1234
    

    PHP can't tell what the data type is because it isn't passed, it's always just a string of POST data, so compare it to "true" to do your checks, like this:

    if($_POST['isClass'] === "true")
    {
      //Code to add class to session cart
    }
    else
    {
      //Code to add pack to session cart
    }
    
    0 讨论(0)
  • 2020-12-03 01:18
    1. Send the data from your javascript as stringified JSON.
    2. Make a PHP function to convert the strings 'true' and 'false' to boolean value.

    Personally I like #2, which goes with Nick Craver's answer.

    0 讨论(0)
  • 2020-12-03 01:25

    This is a bit of an old question, but I'm surprised nobody has posted this here as solution.

    Just use 1 and 0 instead of true and false when you're constructing your ajax requests. When you do a == comparison, they'll be interpreted as true/false.

    JS:

    $.ajax({
      url: '....',
      data: {
        foo: 1,
        bar: 0
      }
    });
    

    PHP:

    <?php
      if ($_GET['foo']) {
         //...
      } else {
         //...
      }
    
      echo $_GET['bar'] ? 'bar is true' : 'bar is false';
    ?>
    
    0 讨论(0)
  • 2020-12-03 01:29

    Also you can use filter_var function with filter FILTER_VALIDATE_BOOLEAN. According to php documentation it

    Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

    So receiving of POST parameter will look like:

    $isClass = filter_var ($_POST['isClass'], FILTER_VALIDATE_BOOLEAN);
    
    0 讨论(0)
提交回复
热议问题