javascript - Ajax 到 PHP 未定义索引作为数据传递 :

标签 javascript php mysql ajax

你好吗?我不明白为什么我的代码中出现未定义索引错误。我已经浏览了该网站上的大部分帖子,并尝试添加数据类型、括号、使用序列化方法等。

<!DOCTYPE html>  <html>
<head>
  <!--Import Google Icon Font-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!--Import materialize.css-->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
  <link rel="stylesheet" href="styles/styles.css" />

  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>

<body>
<div class="container">
    <h1 class="center-align">Welcome to the Black Archives</h1>
    <p id="introparagraph">Thank you for visitng us today. We look forward to serving you. Please take the time to complete the following form. You're contact information will be stored in our system. This information will be used to keep you informed about upcoming events and exhibits. You will also receive a copy of our next newsletter. We will only use your information for museum-related purposes. Your information will not be sold or distributed to another party. For questions related to this form, please stop by the main office.</p>
    <div class="myForm">
        <div class="row">
            <form class="col s12" action="register.php" id="registerForm" method="POST">
                <div class="row">
                    <div class="input-field col s5">
                        <input placeholder="First Name" id="fname" name="fname" type="text" class="validate">
                        <label class="labelText" for="fname">First Name</label>
                    </div>
                    <div class="input-field col s2">
                        <input placeholder="Middle Initial" id="mi" name="mi" type="text" class="validate">
                        <label class="labelText" for="mi">Middle Initial</label>
                    </div>
                    <div class="input-field col s5">
                        <input placeholder="Last Name" id="lname" name="lname" type="text" class="validate">
                        <label class="labelText" for="lname">Last Name</label>
                    </div>
                </div>
                <div class="row">
                    <div class="input-field col s6">
                        <input placeholder="Address" id="address" name="address" type="text" class="validate">
                        <label class="labelText" for="address">Address</label>
                    </div>
                    <div class="input-field col s6">
                        <input placeholder="Address 2" id="address2" name="address2" type="text" class="validate">
                        <label class="labelText" for="address2">Address 2</label>
                    </div>
                </div>
                <div class="row">
                    <div class="input-field col s5">
                        <input placeholder="City" id="city" name="city" type="text" class="validate">
                        <label class="labelText" for="city">City</label>
                    </div>
                    <div class="input-field col s2">
                        <input placeholder="State" id="state" name="state" type="text" class="validate">
                        <label class="labelText" for="state">State</label>
                    </div>
                    <div class="input-field col s5">
                        <input placeholder="Postal Code" id="zipcode" name="zipocode" type="text" class="validate">
                        <label class="labelText" for="zipcode">Postal Code</label>
                    </div>
                </div>
                <div class="row">
                    <div class="input-field col s6">
                        <input placeholder="Email" id="email" name="email" type="email" class="validate">
                        <label class="labelText" for="email">Email Address</label>
                    </div>
                    <div class="input-field col s6">
                        <input placeholder="Phone" id="phone" name="phone" type="tel" class="validate">
                        <label class="labelText" for="phone">Phone</label>
                    </div>
                </div>
                <div class="row right-align">
                      <button class="btn waves-effect waves-light btn-large" type="submit" name="register" id="submitBtn">Submit<i class="material-icons right">send</i></button>
                </div>
            </form>
        </div>
    </div>
</div>

  <script src="js/scripts.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".input-field>label").css("color", "black");

        $("#submitBtn").on('click', function () {
            var fname = $("#fname").val();
            var mi = $("#mi").val();
            var lname = $("#lname").val();
            var address = $("#address").val();
            var address2 = $("#address2").val();
            var city = $("#city").val();
            var state = $("#state").val();
            var zipcode = $("#zipcode").val();
            var email = $("#email").val();
            var phone = $("#phone").val();

            console.log(phone);

            if (fname == "") {
                $('#fname').css("backgroundColor", "#f7e7e1");
            }
            else if (lname == "") {
                $('#lname').css("backgroundColor", "#f7e7e1");
            }
            else {
                $.ajax({
                    url: 'register.php',
                    method: 'POST',
                    data: { data: $('#registerForm').serialize() },
                    success: function (response) {
                        console.log("Hello World!!!");
                    },
                    dataType: 'text'
                });
            }
        });
    });
</script>
</body>

下面是 PHP 文档。当传递数据并通过浏览器的调试工具监视它时,它显示寄存器:没有数据。

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "museum";

    if (isset($_POST['register'])) {        
        $conn = new mysqli($servername, $username, $password, $dbname);

        if($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $fname = $_POST['fname'];
        $mi = $_POST['mi'];
        $lname = $_POST['lname'];
        $address = $_POST['address'];
        $address2 = $_POST['address2'];
        $city = $_POST['city'];
        $state = $_POST['state'];
        $zipcode = $_POST['zipcode'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];

        $sql = "INSERT INTO guest (fname, mi, lname, address1, address2, city, state, zipcode, email, phone) VALUES ('$fname', '$mi', '$lname', '$address', '$address2', '$city', '$state', '$zipcode', '$email', '$phone')";

        if($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $conn->close();
    }
?>

最佳答案

An easier way would be to add an ID to your form and add the name="" attribute to your input fields. Then, when you're going to post them with Ajax, all you need to do is: data: $('#the-form-id').serialize(). No need to define all the fields in JS. – Magnus Eriksson 6 hours ago

这有效,必须取出变量初始化,并将 name 属性添加到每个输入。然后程序按预期运行。

关于javascript - Ajax 到 PHP 未定义索引作为数据传递 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201482/

相关文章:

javascript - 通过坐标对 Canvas 鼠标悬停进行 3/4 按钮的窃听

php - 发送到 $_POST 的 Jquery var 未完成查询,返回错误

mysql - 把WampServer的MySQL当作真正的MySQL上网

mysql - 该更新查询不起作用?

javascript - 从 Google 的反向地理编码中获取地址

javascript - 我如何获得所选选项的值(如显示值而不是值 ="")

javascript - 获取 http.get 数据到本地 JSON 数组变量

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - 无效查询 : You have an error in your SQL syntax; syntax to use near

php - "^/page/(\d+)$"的 preg_match