Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP & AJAX form "Undefined array key" error

I’m trying to send some data from inputs to the database. Everything works (data is sent), but there is an error:
"Undefined array key "name" in C:\xampp\htdocs\whatever.php on line 42" and
"Undefined array key "type" in C:\xampp\htdocs\whatever.php on line 43".
Here is my code:


<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#form').on('submit', function (e) {

          e.preventDefault();
            
          $.ajax({
            type: 'post',
            url: 'whatever.php',
            data: $('form').serialize(),
            success: function () {
              document.getElementById("text").innerHTML = "success";
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form id="form">
      <input name="name"><br>
      <input name="surname"><br>
      <input name="submit" type="submit" value="Submit">
        <p id="text">placeholder</p>
    </form>
  </body>
</html>

<?php

    $con = mysqli_connect("localhost", "root", "", "base");

        $name = $_POST["name"];
        $type = $_POST["surname"];
        $date = date("d.m.Y, G:i");
        $sql = "INSERT INTO product(`name`, `surname`, `date`) VALUES('$name', '$surname', '$date')";

        $var = mysqli_query($con,$sql);

    mysqli_close($con); 

?>

I was trying a few things, but nothing worked. I would appreciate some help to fix this, thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

using isset to check whether there is a key or not.

isset($_POST["name"]) ? $_POST["name"] : null;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading