0

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();
    }
?>
Theo Greer
  • 17
  • 1
  • 5
  • So, where do you get the undefined index? – M. Eriksson May 06 '18 at 15:38
  • 3
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Raymond Nijland May 06 '18 at 15:38
  • 3
    **Warning: You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php)** and should really use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of concatenating your queries. Specially since you're not escaping the user inputs at all! – M. Eriksson May 06 '18 at 15:38
  • in your ajax request there is no register field. try adding it to the query, like so $.ajax(..., data: {register: 'register', ...}) – xanadev May 06 '18 at 15:41
  • 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. – M. Eriksson May 06 '18 at 15:44
  • is zip an int in your db? – Jonny May 06 '18 at 16:00
  • I get the undefined error when I get transferred to the register.php page. Everything loads just fine, and it makes the connection to the database, and runs the JavaScript "success" function, but the data isn't being passed to the register.php page. It is blank. – Theo Greer May 06 '18 at 20:02
  • Thank you Magnus, I'm looking in to that now. – Theo Greer May 06 '18 at 20:04
  • No Jonny, zip is a varchar – Theo Greer May 06 '18 at 20:08
  • @Magnus, I tried to use the serialize() earlier, and it didn't work, but I hadn't added the names to each of the input fields. I've now changed the code, but I'm still getting the same error. I think xanadev is on the right track, but I don't quite understand where this is supposed to take place. I'm passing 'register' but it is empty. – Theo Greer May 06 '18 at 20:15

1 Answers1

0

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.

Theo Greer
  • 17
  • 1
  • 5