Home > Blockchain >  PHP & AJAX form "Undefined array key" error
PHP & AJAX form "Undefined array key" error

Time:07-31

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!

CodePudding user response:

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

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

  • Related