1

I am designing a php application using AJAX and PHP. But the if statement in my php file behaves unexpectedly. The request method is 'POST'; Ajax code is

        function fetchData(){
            var recipename = document.getElementById("recipe").value;
            var calorie = false;
            createRequestObject();
            //window.alert(calorie);
            var url = "reciepinfo.php"; 
            xmlHttp.open("POST",url,true);
            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            window.alert(calorie);
            xmlHttp.send("recipe="+recipename+"&calorie="+calorie);
            xmlHttp.onreadystatechange = function(){
                if(xmlHttp.readyState===4 && xmlHttp.status===200){                       
                    document.getElementById("target").innerHTML = xmlHttp.responseText;                                          
                }
            }
        } 

And php code is:

  <?php
 $_SESSION['flag']=false;
if($_SESSION['flag']==false){
    session_start(); 
    $_SESSION['flag']=true;
}
$recipename = $_REQUEST['recipe'];
$calorie = $_REQUEST['calorie'];  
 echo $calorie;
 $calorietemp = 0;
 //echo $recipename;
 $database = "nutrition";
 $link = mysqli_connect('localhost','root','',$database);
 $query = "select * from recipestb where name='$recipename'";
 //$result = mysqli_query($link,$query);
 //$obj = mysqli_fetch_object($result);;
 if($link){
    $result = mysqli_query($link,$query);
    $obj = mysqli_fetch_object($result);
    //$arr = mysqli_fetch_array($result);
   //$names = "";
    if(is_object($obj)){
            echo "<i/>";
            echo "<font size='5'>";
            echo "Recipe name: ".$obj->name;
            echo '<br/>';
            echo "Carbohydrates : ".$obj->carbs." grams";
            echo '<br/>';
            echo "Proteins: ".$obj->protein." grams";
            echo '<br/>';
            echo "Fat: ".$obj->fat." grams";
            echo '<br/>';
            echo "Calories: ".$obj->calorie." cal";
            $calorietemp = $obj->calorie;
            echo '<br/>';    

    }else{
        echo "non object";
    }

 }else{
     echo "Connection failed";
 }
if($calorie==true){
     echo $calorie;
     $_SESSION['caloriecount'] = $_SESSION['caloriecount'] + $calorietemp;           
     echo "Total calorie in diet :".$_SESSION['caloriecount'];          
}

My session handling is weird i accept, but neglecting that, even the variable calorie is explicitly set to false, the if block executes.The echo $calorie statement also executes and it displays $calorie as false. And i am not getting what is going wrong exactly. Almost irritated with this. Can anybody help?

EDIT1: The php code is fine... Ajax code has some problem... When i set the $calorie to false in php code.. It behaved properly..

6
  • 2
    I suspect this might have to do with variable types. Are you sure $calorie is a boolean? If it has the string value "false", it would evaluate to boolean true in the if-statement, but still come out as false when you echo. Commented Oct 31, 2015 at 12:18
  • @Abhishek Malakar nah still not working.. Commented Oct 31, 2015 at 12:18
  • @Anders see in the fetchData() ... i have set it to false.. Commented Oct 31, 2015 at 12:19
  • 1
    Not sure the type information is preserved through the AJAX call to the PHP. Try running $calorie = (strtolower($calorie) === 'true'? true: false;); somewhere before the if statement. Not sure about this, though. Just guessing. But it is worth a try. Commented Oct 31, 2015 at 12:23
  • 1
    Glad that you solved the issue! Instead of editing the question, you should post your solution to the problem as an answer, and accept it (or some other answer that helped). Commented Nov 1, 2015 at 2:01

2 Answers 2

2

Leaving the session handling aside, the $calorie problem ... You pass the data via AJAX as strings.

$calorie = 'false';
var_dump((true == $calorie));

You will get always bool(true). Using your AJAX example above, try this snippet instead (and use POST instead of REQUEST):

$calorie = ('true' == $_POST['calorie']);
var_dump($calorie);
// produces `bool(false)`
Sign up to request clarification or add additional context in comments.

6 Comments

I know ... revised my posting - your problem is $_POST variable handling and types. false and 'false' have different meaning.
That might be the issue let me check.. wait
I used $calorie = boolval($_POST['calorie']); And passed '1' and '0' values as $calorie using java-script as per requirement. And problem solved! Sorry for the trouble
boolval is good idea, yet available PHP > 5.5. hint: Vote up anyone who helped :)
Haven't tried your solution.. Will try n let you know.. Thank you!
|
0

As a beginner i was unaware that the java-script variable with value false is passed as a string "false" to a server side script like PHP.

If we use a boolval(), in PHP this issue can be resolved. PHP boolval()

I set the $calorie in my java-script to 0 or 1 as per my need. When i wanted the false value to be sent to PHP script ,i set $calorie in java-script to 0 and the boolval() in corresponding PHP script evaluated it as false. So the issue was resolved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.