0

In the table in the database contains the column date, checkbox. How can I disable the checkbox if the inputted date is already in the database.For example, if in the table contains date = 13/9/2019 and checkbox = h1, then if we input the date 13/9/2019, the checkbox h1 is disabled and vice versa

$(document).ready(function {
  $("#date").change(function {
    var date = $("#date").val();

    $.ajax({
      url: "variable.php",
      method: "POST",
      data: {
        date2: date
      },
      dataType: "text",
      success: function(html) {
        //what to put here?
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date">
<input type="checkbox" name="checkbox[]" id="checkbox" name="h1">
<input type="checkbox" name="checkbox[]" id="checkbox" name="h2"">
<?php  $db = mysqli_connect('localhost','root','','mydatabase');
if (isset($_POST['date2'])){
$query = mysqli_query($db, "SELECT * FROM mytable where date = 
 '".$_POST["date2"]."'");
// what to put here?
}
?>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

5 Answers5

2

First of all your PHP script needs improvement. You should enable error reporting and use prepared statements. The value should also be validated before use.

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost','root','','mydatabase');
$db->set_charset('utf8mb4');

if (isset($_POST['date2'])) {
    $date = (new DateTime($_POST["date2"]))->format('Y-m-d'); //validate format
    // prepare -> bind -> execute
    $stmt = $query = $db->prepare("SELECT 1 FROM mytable WHERE date = ? ");
    $stmt->bind_param('s', $date);
    $stmt->execute();
    // get a single column from the first row of the mysql result
    $exists = (bool)$stmt->get_result()->fetch_row();

    // send JSON response to AJAX
    echo json_encode(['exists' => $exists]);
}

Then in your AJAX you need to check the returned value.

$(document).ready(function {
  $("#date").change(function {
    var date = $("#date").val();

    $.ajax({
      url: "variable.php",
      method: "POST",
      data: {
        date2: date
      },
      dataType: "text",
      success: function(response) {
        $obj = JSON.parse(response); // Since the datatype is text we need to make in a valid JSON
        $("#checkbox_h1").attr("disabled", $obj.exists); // $obj.exists has the return value from mysql
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date">
<input type="checkbox" name="checkbox[]" id="checkbox_h1" name="h1">
<input type="checkbox" name="checkbox[]" id="checkbox_h2" name="h2"">

This is a very rough code to only give you an idea. You can write something similar.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • `fetch_row()[0]` shortcut would result in the undefined index error if no record found. it should be either the way I edited the code or count(1) in the query. another reason why PDO is better - no such quirk there :) – Your Common Sense Sep 26 '19 at 09:27
  • @YourCommonSense I tested it (PHP 7.2.5) and I can't the error message. I must be doing something wrong. Nevertheless, the way you proposed seems to be better. – Dharman Sep 28 '19 at 22:11
  • Look, fetch_row() returns false when no results found. And trying to access an array element from false will [produce an error](https://3v4l.org/b35YD) – Your Common Sense Sep 29 '19 at 05:34
  • @YourCommonSense I see, so it only has been added in PHP 7.4. https://wiki.php.net/rfc/notice-for-non-valid-array-container – Dharman Sep 29 '19 at 09:46
  • Oh crap. I had no idea of this behavior and even overlooked my own example. My apologies. – Your Common Sense Sep 29 '19 at 10:40
0

In you php file put.

 <?php  $db = mysqli_connect('localhost','root','','mydatabase');
 if (isset($_POST['date2'])){
 $result = mysqli_query($db, "SELECT * FROM mytable where date = 
  '".$_POST["date2"]."'");
   if ($result) 
   { 
     // it return number of rows in the table. 
     $row = mysqli_num_rows($result); 

     if($row > 0){
          echo 1; //exist
     } else {
          echo 0; // not exist
     // close the result. 
     mysqli_free_result($result); 
   } 
 }
 ?>

and in ajax

$.ajax({
  url: "variable.php",
  method: "POST",
  data: {
    date2: date
  },
  dataType: "text",
  success: function(html) {
    if(html == 1){
        // hide checkbox
        $(".checkboxClass").attr("disabled","disabled");
    }
  }
});
Sanjun Dev
  • 518
  • 8
  • 20
0

you should return true|false in ajax success callback and place below code in success call back

$.ajax({
  url: "variable.php",
  method: "POST",
  data: {
    date2: date
  },
  dataType: "text",
  success: function(result) {
   if(result == true || result == 'true'){ // # just to be safe side
       $("input[type='checkbox']").attr("disabled",true); // #disable the checkbox
    }
  }
});
Ashok Damaniya
  • 303
  • 1
  • 6
-1

After mysqli_query do something like this

if (isset($_POST['date2'])){
    $query = mysqli_query($db, "SELECT * FROM mytable where date = '".$_POST["date2"]."'");
    if (mysqli_num_rows($query) > 0)
    {
        // print/echo or return(if a return-function) - true/1/successful
        // eg.
        print 1;
        exit();
    }
}

And get the result in Ajax response

$.ajax({
  url: "variable.php",
  method: "POST",
  data: {
    date2: date
  },
  dataType: "text",
  success: function(html) {
    //what to put here?
    if (html == 1) {
        //disable checkbox
    }
  }
});
lkdhruw
  • 572
  • 1
  • 7
  • 22
-1
<?php  
$db = mysqli_connect('localhost','root','','mydatabase');
if (isset($_POST['date2'])){
    $query = mysqli_query($db, "SELECT * FROM mytable where date = 
           '".$_POST["date2"]."'");
    // what to put here?
    retunr mysqli_num_rows($query);
}
?>

First return the number of rows. If the number of rows is greater than 0, it means the date exists in the databsae. On the front end check this and disable the checkbox if it is greater than 0.

$(document).ready(function {
  $("#date").change(function {
    var date = $("#date").val();

    $.ajax({
      url: "variable.php",
      method: "POST",
      data: {
        date2: date
      },
      dataType: "text",
      success: function(html) {
        if(html > 0){
          $('#checkbox').attr("disabled", true);
        }
      }
    });
  });
});
UnleashDchaos
  • 475
  • 1
  • 4
  • 15