skip to Main Content

I am trying to disable the particular date whose count of the particular date is 8. In my code the particular date cannot be used after 8 counts..After 8 counts alert box appears. Instead of alert box i have to disable the particular date.. How can i disable the date.. Here is the code.

<input type="date" name="mass_date" id="txtDate" required="required" /></div>

<script>  
         $(document).ready(function() {
            $('#txtDate').change(function(){
                var selectedDate = $(this).val();
                $.ajax({
                    type: 'GET',
                    url: "http://localhost/check_date.php?selectedDate=" +selectedDate, 
                    success: function(data) {
                        var status= JSON.parse(data);
                        if((status=="SUCCESS")) {
                            $('#submitButton').prop('disabled', false);
                        } else {
                            alert('Opps! Booking is not available for this day');
                        }
                    }
                });
            });
        });
    </script>

check_date.php

<?php 
    error_reporting(E_ALL);
    include_once "db.php";
    $selectedDate = $_GET['selectedDate'];

    $query2=mysqli_query($con,"SELECT COUNT(*) as booking_count FROM shrine_mass WHERE mass_date='$selectedDate'") or die(mysqli_error($con));
    $row=mysqli_fetch_array($query2,MYSQLI_ASSOC);
    $count = $row['booking_count'];
    if($count < 8) {
        echo json_encode("SUCCESS");

    } else {
        echo json_encode("FAIL");
    }

2

Answers


  1. EDIT: Scroll down!

    WARNING You are wide open to SQL Injections (SQLI Attacks). Please make use of Prepared Statements and Parametized queries.

    With that said, I will be rewriting your PHP page to follow the guidelines of Prepared Statements and Parametized queries.

    As for the jQuery part of your question, I believe what you’re looking for is the property function, .prop("disabled", true);. You already used it for your submitButton, except there you enable the button by setting the property to false.

    jQuery Exampled, using your code:

     $(document).ready(function() {
        $('#txtDate').change(function(){
            var selectedDate = $(this).val();
            $.ajax({
                type: 'GET',
                url: "http://localhost/check_date.php?selectedDate=" +selectedDate, 
                success: function(data) {
                    var status= JSON.parse(data);
                    if((status=="SUCCESS")) {
                        $('#submitButton').prop('disabled', false);
                    } else {
                        $('#txtDate').prop("disabled", true);
                    }
                }
            });
        });
    });
    

    Your PHP page, using Prepared Statement and Parametized query:

    <?php
    // Your input GET variable
    $selectedDate = $_GET['selectedDate'];
    
    // DB variables
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // Check connection
    if($conn->connect_error){
      die("Connection failed: " . $conn->connect_error);
    }
    
    // Declare the query
    $sql = "SELECT COUNT(*) as booking_count FROM shrine_mass WHERE mass_date = ?";
    
    // Prepare and bind
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $selectedDate);
    
    // Execute the query
    $stmt->execute();
    
    // Bind result variable and fetch value
    $stmt->bind_result($booking_count);
    $stmt->fetch();
    
    // Close connection
    $stmt->close();
    $conn->close();
    
    if($booking_count < 8) {
        echo json_encode("SUCCESS");
    
    } else {
        echo json_encode("FAIL");
    }
    ?>
    

    Snippet example, displaying the .prop("disabled", true); in action:

     $(document).ready(function() {
    	$('#txtDate').prop("disabled", true);
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="row d-flext justify-content-center">
    	<div class="col-md-4">
    		<input type="date" name="mass_date" id="txtDate" class="form-control" required="required" />
    	</div>
    </div>

    Codepen Example here.

    EDIT:

    Since you wanted to disable a specific date in particular depending on the count of that date in your database, then I would recommend using either jQuery datepicker or Bootstrap datepicker. I will move forward using jQuery datepicker.

    More about jQuery datepicker here.

    First you will need to query your database for the dates where your logic applies, i.e. where the date occurs more than 8 times.

    Example:

    SELECT
        mass_date
    FROM
        mass_table
    GROUP BY
        mass_date
    HAVING
        COUNT(*) > 8;
    

    DB Fiddle here.

    The idea is that you create a JavaScript array, which contains the dates you want to disable. You then want to populate this array with the dates that fit your logic.

    This is how your main page could look like:

    <?php
    // DB variables
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // Check connection
    if($conn->connect_error){
      die("Connection failed: " . $conn->connect_error);
    }
    
    // Declare the query
    $sql = "SELECT mass_date FROM mass_table GROUP BY mass_date HAVING COUNT(*) > 8";
    
    // Prepare
    $stmt = $conn->prepare($sql);
    
    // Execute the query
    $stmt->execute();
    
    // Get result of query
    $result = $stmt->get_result();
    
    // Close connection
    $stmt->close();
    $conn->close();
    ?>
    
    <script>
    // The array containing the dates to be disabled in the datepicker
    let disabledDates = [];
    
    <?php
    // Loop through our query results
    while($data = $result->fetch_assoc()) {
        ?>
        // Push the dates into the disabledDates array
        disabledDates.push("<?php $data['mass_date']; ?>");
        <?php
    }
    ?>
    
    // jQuery datepicker function
    $('#txtDate').datepicker({
        beforeShowDay: function(date){
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [ disabledDates.indexOf(string) == -1 ]
        }
    });
    </script>
    
    <div class="row d-flext justify-content-center">
        <div class="col-md-4">
            <input type="date" name="mass_date" id="txtDate" class="form-control" required="required" />
        </div>
    </div>
    

    Codepen Example of jQuery datepicker disabled dates here.

    Login or Signup to reply.
  2. As I understand your question, you are looking to prevent the user entering a given date once it has been selected 8 times by other users. Using @Martin’s answer, you will disable the date input altogether, and I don’t think this is what you are after. I presume you are looking for a solution that would prevent the entry of a ‘fully booked’ date, but not the input of other dates.

    I don’t think you can stop any date being selected in a type=”date” INPUT. There are attributes to restrict the input to a date range, but not to restrict particular dates
    from within a range.

    So the only possible solution must involve checking a newly entered date against some data to determine if it can be used. You are currently doing this during your ajax call, and frankly, assuming your application is available to multiple users simultaneously, this is the only viable approach. Any data you might pass to the browser on page load could be rendered ‘out of date’ seconds later by the actions of another user.

    So my answer to your question is No, there is no way to achieve what you want that is better than your current strategy, or some variation of it that references your database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search