如何使用Ajax在PHP和MySQL中使用Bootstrap Datepicker

在本教程中,我将解释如何使用Ajax在PHP和MySQL中实现Bootstrap Datepicker。我将一步一步地指导你如何工作。所以在这个例子中,我们将创建一个函数,询问用户的出生日期。

在Bootstrap Datepicker的帮助下,我们可以用一个优秀的用户界面来实现一个快速的过程,而不是从头开始做,或者只是在chrome上使用不支持其他浏览器的本地日期选择器。

Index.html文件

以下是index.html的完整源代码:

<!doctype html>
<html lang="en">
<head>
    <title>How To Use Bootstrap Datepicker in PHP & MySQL using Ajax</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <!-- Bootstra Datepicker CSS -->
    <link rel="stylesheet" href="assets/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css">

</head>

<body>

    <div class="container">

        <br><br>

        <h1>How To Use Bootstrap Datepicker in PHP & MySQL using Ajax</h1>

        <br><br>

        <form action="process.php" id="form">
            <div class="form-group">
                <label for="email">Date Of Birth:</label>
                <input class="date form-control" type="text" name="date-of-birth">
            </div>
            <button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>
        </form>
    </div>

    <!-- Must put our javascript files here to fast the page loading -->

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Bootstrap Datepicker JS -->
    <script src="assets/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
    <!-- Page Script -->
    <script src="assets/js/scripts.js"></script>

</body>

</html>

Script.js文件 

接下来,我们的javascript被称为scripts.js,从上面的代码中导入。请检查每一行的注释,以便你了解这个过程。

$(document).ready(function() {

    // Initialize the datepicker
    $('.date').datepicker({
        todayHighlight: true, // to highlight the today's date
        format: 'yyyy-mm-dd', // we format the date before we will submit it to the server side
        autoclose: true //we enable autoclose so that once we click the date it will automatically close the datepicker
    }); 

    $("#btnSubmit").on("click", function() {
        var $this           = $("#btnSubmit"); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                $this.attr('disabled', false).html($caption);
                // We will display the result using alert
                alert(response);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });


});

创建数据库表 

接下来,创建我们的数据库表。如果你已经创建了你的数据库,那么我们将继续创建我们的表 "dob "作为你的表名。下面是代码:

CREATE TABLE `dob` (
  `id` int(11) NOT NULL,
  `dob` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Process.php文件 

接下来,我们的最后一段代码是处理保存提交的数据:

<?php
    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $date = $request['date-of-birth']; //get the date of birth from collected data above

    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
    }

    // Set the INSERT SQL data
    $sql = "INSERT INTO dob (dob)
    VALUES ('".$date."')";

    // Process the query so that we will save the date of birth
    if (mysqli_query($conn, $sql)) {
      echo "New record created successfully.";
    } else {
      return "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    // Close the connection after using it
    mysqli_close($conn);
?>

现在,你可以通过使用PHP和MySQL的Ajax,使bootstrap datepicker保存表单中的数据。 

猜你喜欢

转载自blog.csdn.net/o67f2wpkvdf3bpe8/article/details/130097737