Skip to content
Advertisement

Dropdown selection based on other dropdown [closed]

I am working on a webform that will allow the user to simulate a purchase of a movie ticket.

The date/time should change dynamically based on the movie selection. The data is retrieved from the database, and ajax is used to achieve this.

The problem is when I select the movie, the div of date/time disappear, I am probably doing something wrong I guess.

To follow, I have attached the code and the database data.

Index page:

<!DOCTYPE html>
<html lang="en">
    <head>
            <?php
                require_once("php/connection.php");
                    $query = "SELECT movieID,title FROM movie";
                    $result1 = mysqli_query($conn,$query);
            ?>
            <meta charset="utf-8">
            <title>Bollywood movies | Tickets</title>
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" type="text/css" href="css/Style.css">
            <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
            <script src="js/jquery-3.5.1.min.js"></script>
    </head>
    <body>
        <header>
        <h1>Bollywood movies</h1>
        </header>
        <section class="banner">
            <img src="images/third-serving-nLl5sJnElxY-unsplash.jpg" alt="Movies">
        </section>
        <nav id="navbar">
            <ul>
                <li><a href="">Home</a> </li>
                <li>  <a href="">Bookings</a> </li>
                <li> <a href="">Coming soon..</a> </li>
            </ul>
        </nav>
        <h2>You can book your tickets here!</h2>
        <form action="php/action.php" method="post" onsubmit="return validateForm()" id="form">
            <div id="customer">
                <div id="first">
                    <label for="fname">First Name</label><br>
                    <input type="text" id="fname" name="fname" class="fields"><br>
                </div>
                <div id="last">
                    <label for="lname">Last Name</label><br>
                    <input type="text" id="lname" name="lname" required class="fields"><br>
                </div>
                <div id="Email">
                    <label for="email">Email</label><br>
                    <input type="email" id="email" name="email" required class="fields"><br>
                </div>
                <div id="mobile">
                    <label for="Mobile_Number">Mobile Number</label><br>
                    <input type="text" id="Mobile_Number" name="Mobile_Number" required class="fields"><br>
                </div>
            </div>
            <div id="movie" >
                <div id="Movies">
                    <label for="movies">Movie selection</label><br>
                    <select name="movies" id="movies" class="fields">
                    <option selected="" disabled="" >Select movie</option>
                    <?php 
                    while($row = mysqli_fetch_array($result1)):; ?>
                        <option  value=" <?php echo $row['movieID']; ?>"><?php echo $row['title'];?></option>
                    <?php endwhile;
                    ?>
                    </select> <br>
                </div>
                <div id="Date">
                    <label for="date">Session date/time</label><br>
                    <select name="date"  id="date" class="fields" >
                    <option  value="">Select date/time</option>
                    </select> 
                </div>
            <div>
            </div id="credit">
                <div id="card" class="hide">
                    <label for="Credit_card">Credit card number</label><br>
                    <input type="tel" id="Credit_card" name="credit" class="fields" ><br>
                </div>
            </div>
            <br>
            <div id="submit">
                <input class="fields" id="sub" type="submit" value="Submit">
                <input class="fields" type="reset">
            </div>
            <br>
            <hr>
            <br>
            <span id="error_message"></span>
            <span id="success_message"></span>
            <div id="yes"> </div>
        </form>
        <script>
                $("#fname, #lname, #email, #Mobile_Number").change(function() {
                if ($(this).val() .length == 0) {
                $('#movie').hide();
                } else {
                $('#movie').show();
                }
                });
                $("#fname, #lname, #email, #Mobile_Number").trigger("change");

                $("#movie, #Date").change(function() {
                if ($(this).val() .length == 0) {
                $('#credit').hide();
                } else {
                $('#credit').show();
                }
                });
                $("#movie, #Date").trigger("change");
        </script>
        <script>
                $(document).on('change','#movies', function() { 
                    var movieID = this.value;
                    if(movieID){
                        $.ajax({
                            type:'POST',
                            url:'php/ajaxData.php',
                            data:'movieID'+movieID,
                            success:function(html){
                                $('#Date').html(html);
                            } 
                        });
                    } else {
                        $('#Date').html('<option value="">Select date/time</option>');
                    }
                });
        </script>
        <script>
                function validateForm() {
                var x = document.forms["form"]["fname"].value;
                if (x == "") {
                    alert("Name must be filled out");
                    return false;
                }
                }
        </script>
         <script>
                var name= $('#fname').val() ;
                var lname= $('#lname').val() ;            
                $('#sub').click(function() {
                alert("Thank you for your booking, " + $( '#fname' ).val() + " " + $('#lname').val() + " , have a great day! " );
                });
        </script>

ajaxData.php:

<?php
include_once 'connection.php';

if(!empty($_POST["movieID"])){

    $query = "SELECT * FROM sessions WHERE movieID = ".$_POST['movieID']." " ;
    $result = $db->query($query);
    

    if($result->num_rows > 0){
        echo '<option value="">Select date/time</option>';
        while($row = $result->fetch_assoc()){
            echo'<option value="'.$row['movieID'].'">'.row['sessionDate'].'</option>';
        }
    } else {
        echo '<option value="">Date not available</option>';
    }

}
?>

Database:

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 11, 2021 at 03:48 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.10

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `bollywood_movies`
--

-- --------------------------------------------------------

--
-- Table structure for table `booking`
--

CREATE TABLE `booking` (
  `bookingID` int(11) NOT NULL,
  `patronID` int(11) NOT NULL,
  `sessionID` int(11) NOT NULL,
  `paid` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- --------------------------------------------------------

--
-- Table structure for table `movie`
--

CREATE TABLE `movie` (
  `movieID` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `year` int(4) NOT NULL,
  `active` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `movie`
--

INSERT INTO `movie` (`movieID`, `title`, `description`, `year`, `active`) VALUES
(1, 'The Godfather', 'Gangsters movie with plenty of suspance', 1972, 1),
(2, 'Raging Bull', 'The story of a bull that was raging', 1980, 1),
(3, 'Schindlers list', 'history movie about the war', 1993, 1),
(4, 'The Shawshank Redemption', 'The redemption of the shanks', 1994, 1),
(5, 'Casablanca', 'Crime and action', 1942, 1);

-- --------------------------------------------------------

--
-- Table structure for table `patron`
--

CREATE TABLE `patron` (
  `patronID` int(11) NOT NULL,
  `first_name` varchar(200) NOT NULL,
  `last_name` varchar(200) NOT NULL,
  `email` varchar(100) NOT NULL,
  `mobile` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- --------------------------------------------------------

--
-- Table structure for table `sessions`
--

CREATE TABLE `sessions` (
  `sessionID` int(11) NOT NULL,
  `movieID` int(11) NOT NULL,
  `sessionDate` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `sessions`
--

INSERT INTO `sessions` (`sessionID`, `movieID`, `sessionDate`) VALUES
(1, 1, '2020-12-23 18:51:33'),
(2, 2, '2020-12-16 10:25:33'),
(3, 3, '2020-12-31 09:51:33'),
(4, 4, '2020-12-29 11:51:33'),
(5, 5, '2020-12-17 22:51:33');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `booking`
--
ALTER TABLE `booking`
  ADD PRIMARY KEY (`bookingID`),
  ADD KEY `patronID` (`patronID`),
  ADD KEY `sessionID` (`sessionID`);

--
-- Indexes for table `movie`
--
ALTER TABLE `movie`
  ADD PRIMARY KEY (`movieID`);

--
-- Indexes for table `patron`
--
ALTER TABLE `patron`
  ADD PRIMARY KEY (`patronID`);

--
-- Indexes for table `sessions`
--
ALTER TABLE `sessions`
  ADD PRIMARY KEY (`sessionID`),
  ADD KEY `movieID` (`movieID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `booking`
--
ALTER TABLE `booking`
  MODIFY `bookingID` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `movie`
--
ALTER TABLE `movie`
  MODIFY `movieID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `patron`
--
ALTER TABLE `patron`
  MODIFY `patronID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34;

--
-- AUTO_INCREMENT for table `sessions`
--
ALTER TABLE `sessions`
  MODIFY `sessionID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `booking`
--
ALTER TABLE `booking`
  ADD CONSTRAINT `booking_ibfk_1` FOREIGN KEY (`patronID`) REFERENCES `patron` (`patronID`),
  ADD CONSTRAINT `booking_ibfk_2` FOREIGN KEY (`sessionID`) REFERENCES `sessions` (`sessionID`);

--
-- Constraints for table `sessions`
--
ALTER TABLE `sessions`
  ADD CONSTRAINT `sessions_ibfk_1` FOREIGN KEY (`movieID`) REFERENCES `movie` (`movieID`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

I have been working on this for a while and still learning but it doesn’t seem to work for some reason.

Any help will be appreciated… Thanks

Advertisement

Answer

You have couple of errors:

1.Index page

var movie = this.value;
...
$.ajax({
    type:'POST',
    url:'php/ajaxData.php',
    data:{movieID: movie},
    success:function(html){
       $('select#date').html(html);//<--here
    } 
});

2.ajaxData.php

<?php
include_once 'connection.php';
$out = ''; //initial string
if(isset($_POST["movieID"])){//here
    $stmt = $mysql->prepare("SELECT * FROM sessions WHERE movieID = ?");
    $stmt->bind_param('i', $_POST["movieID"]);
    $stmt->execute();
    $result = $stmt->get_result();
    

    if($result->num_rows > 0){
        $out .= '<option value="">Select date/time</option>';
        while($row = $result->fetch_assoc()){
            $out .= '<option value="'.$row['movieID'].'">'.row['sessionDate'].'</option>';
        }
    }
    $stmt->close();
} else {
    $out .= '<option value="">Date not available</option>';
}
echo $out;//Return final result;
?>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement