dimanche 28 juillet 2019

Checking boolean variable from JQuery POST in PHP

I am new in PHP.

I have a variable in jquery called editMode set to false. I used $.post() in jquery to pass the variable in a php function. But when I check its value, the value is fine, but if statement does not function the way it's supposed to. Here is my code:

jQuery (just a snippet):

var editMode = false;
$(document).ready(function(){
    //some function that handles UI input that triggers editMode=true

    $("#form").submit(function(event){
      event.preventDefault();

      var fName = $("#firstname").val();
      var lName = $("#lastname").val();
      //... and the rest of post values coming from UI input

      $.post('includes/sql/register.php', {
         fName: fName,
         lName: lName,
         //... and the rest of post values coming from UI input
         editMode: editMode // this is where I post the value for editMode
      },
      //jQuery function to handle the result
});

In my register.php:

<?php
  if(isset($_POST['submit'])){
     $fName = mysqli_escape_string($conn,$_POST['fName']);
     $lName = mysqli_escape_string($conn,$_POST['lName']);
     //and other post values from UI input
     $editMode = $_POST['editMode'];

     if($editMode) {
        echo $editMode . ": edit"; //fires update query
     } else {
        echo  $editMode . "add"; //fires insert query
     }
  } 
?>

When testing the code, it returns the correct value of $editMode, but does not perform the if statement correctly. What I mean is, if $editMode is true, it echoes: true: edit, which is good. But when it's false, it echoes: false: edit. So it still performs the if clause, even if its value is now false. I also tried if($editMode === true) {//edit} else {//add}, and it does the opposite. Whether $editMode is true or false, it performs the else clause. Please enlighten me.

Aucun commentaire:

Enregistrer un commentaire