首页 > 解决方案 > 基于其他下拉列表的 ajax 和 jQuery 动态下拉列表(来自数据库的数据)

问题描述

我正在使用连接到数据库的表单的网站上工作,用户应该能够根据电影(从数据库收集的数据)选择电影的日期。

我还想在提交表单后向用户显示一条消息,它的代码在此页面末尾被注释掉,它工作但由于某种原因在显示消息后表单不再提交到数据库如果没有它可以正常工作,如何在提交表单后立即显示消息?

我尝试了很多不同的方法,而且我是 ajax 新手,下面是代码:

索引页面:

<!DOCTYPE html>
<html lang="en">
    <head>
    <script>
        $(document).ready(function(){
            $('#movies').on('change',function(){
                var movieID = $(this).val();
                if(movieID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'movieID'+movieID,
                        success:function(html){
                            $('#date').html(html);
                        }
                    });
                } else {
                    $('#date').html('<option value="">Select date/time</option>');
                }
            });
        });
    </script>
        <?php
            require_once("php/connection.php");
           
                $query = "SELECT title FROM movie";
                $result1 = mysqli_query($conn,$query);
        ?>
        <script>
            function validateForm() {
            var x = document.forms["form"]["fname"].value;
            if (x == "") {
                alert("Name must be filled out");
                return false;
            }
            }
        </script>
            <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>

    <h1>Bollywood movies</h1>

    <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="first">
            <label for="fname">First Name</label><br>
            <input type="text" id="fname" name="fname" ><br>
        </div>
        <div id="last">
            <label for="lname">Last Name</label><br>
            <input type="text" id="lname" name="lname" required><br>
        </div>
        <div id="Email">
            <label for="email">Email</label><br>
            <input type="email" id="email" name="email" required><br>
        </div>
        <div id="mobile">
            <label for="Mobile_Number">Mobile Number</label><br>
            <input type="text" id="Mobile_Number" name="Mobile_Number" required><br>
        </div>
        <div id="card">
            <label for="Credit_card">Credit card number</label><br>
            <input type="tel" id="Credit_card" name="credit" ><br>
        </div>
        <div id="Movies">
            <label for="movies">Movie selection</label><br>
            <select name="movies" id="movies">
            <option selected="" disabled="">Select movie</option>
            <?php 
            while($row = mysqli_fetch_array($result1)):; ?>
                <option value=" <?php echo $row[0]; ?>"><?php echo $row[0];?></option>
             <?php endwhile;
            ?>
            </select> <br>
        </div>
        <div id="Date">
            <label for="date">Session date/time</label><br>
            <select name="date" id="date" >
            <option value="">Select date/time</option>
        </div>
        <br>
        <br>
        <hr>
        <div id="submit">
            <input type="submit" value="Submit">
            <input type="reset">
        </div>
        <br>
        <div id="yes"> </div>
    </form>
      
    <script>
            $("#fname").change(function() {
            if ($(this).val() .length == 0) {
            $('#last').hide();
            } else {
            $('#last').show();
            }
            });
            $("#fname").trigger("change");
            
            $("#lname").change(function() {
            if ($(this).val() .length == 0) {
            $('#Email').hide();
            } else {
            $('#Email').show();
            }
            });
            $("#lname").trigger("change");
            
            $("#email").change(function() {
            if ($(this).val() .length == 0) {
            $('#mobile').hide();
            } else {
            $('#mobile').show();
            }
            });
            $("#email").trigger("change");
            
            $("#Mobile_Number").change(function() {
            if ($(this).val() .length == 0) {
            $('#card').hide();
            } else {
            $('#card').show();
            }
            });
            $("#Mobile_Number").trigger("change");
            
            $("#Credit_card").change(function() {
            if ($(this).val() .length == 0) {
            $('#Movies').hide();
            } else {
            $('#Movies').show();
            }
            });
            $("#Credit_card").trigger("change");
            
            $("#movies").change(function() {
            if ($(this).val() .length == 0) {
            $('#Date').hide();
            } else {
            $('#Date').show();
            }
            });
            $("#movies").trigger("change"); 
    </script>

<!-- <script>
            var name= $('#fname').val() ;
            var lname= $('#lname').val() ;            

            $('#form').submit(function() {
            $('#yes').text("Thank you for your booking, " + $( '#fname' ).val() + " " + $('#lname').val() );
            return false;
            });
    </script> -->


</html>

ajax页面:

<?php
include_once 'php/connection.php';

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

    $query = "SELECT sessionDate 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>';
    }

}
?>

连接页面:

<?php
// Set the values for the variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "bollywood_movies";

// Connect to the mySQL database
$conn = @mysqli_connect($servername, $username, $password, $database);

// Check for valid connection. If there are errors display a error message and error details

if (!$conn) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; // Display the MySQL error number
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; // Display the MySQL error details
    exit;
}
?>

动作页面:

<?php
// MySQL Database Connect
require_once("connection.php");
// Read the values from the form
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
$email = $_POST['email'];
$mobile = $_POST['Mobile_Number'];
$movieID = $POST['movies'];
$sessionDate = $_POST['date'];
// escape variables for security
$first_name = mysqli_real_escape_string($conn, $first_name);
$last_name = mysqli_real_escape_string($conn, $last_name);
$email = mysqli_real_escape_string($conn, $email);
$mobile = mysqli_real_escape_string($conn, $mobile);
$movieID = mysqli_real_escape_string($conn, $movieID);
$sessionDate = mysqli_real_escape_string($conn, $sessionDate);

// create the INSERT query
$query="INSERT INTO patron (first_name, last_name, email, mobile) VALUES ('$first_name', '$last_name','$email', '$mobile' )";
$results = mysqli_query($conn, $query );

if(!$results) {
    echo ("Query error: " . mysqli_error($conn));
    exit;
}
else {
    // Redirect the browser window back to the add customer page
    header("location: ../index.php");
}
?>

数据库数据:

--
-- 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 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

--
-- 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 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;

非常感谢您提前提供的帮助,我希望我能够解决这个问题,因为我一直在努力解决这个问题。

标签: phpjquerysqlajax

解决方案


如果我理解正确,您希望在提交表单之后而不是之前出现一条消息,因为让它出现在之前会阻止表单提交?如果您在提交表单后返回页面,您是否可以在标题中设置一个变量,以便 php 代码可以$_GET使用该变量并使用它来显示类似这样的消息

<?php if(isset($_GET['formsubmit']) && $_GET['formsubmit'] == 'pass'){echo'$('#yes').text("Thank you for your booking, '.$_SEASSON['firstname'].' '.$_SEASSON['lastname']).'.';'}?>

或者,如果您不想将名称设置为会话变量,则可能只需设置 parton_id 或其他内容,并进行查询以获取表单的相关信息。不确定这真的算作答案,但我没有足够好的声誉来发表评论。


推荐阅读