简体   繁体   中英

Ajax to PHP Undefined Index Passed as data:

how are you doing? I can't figure out why I'm getting an Undefined Index error in my code. I've been through most of the postings on this site, and tried adding the dataType, the parentheses, using the serialize method, etc.

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

And here is the PHP document below. When Passing the data, and monitoring it via the browser's debugging tool, it shows register: with no data.

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

This worked, had to take out the variable initializations, and add the name attribute to each of the inputs. Then the program worked as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM