Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Post Fatal Error Column Cannot Be Null

I'm getting a fatal error, "Column cannot be null."

index.php

<head>
  <script>
    let xhr = window.XMLHttpRequest
      ? new XMLHttpRequest()
      : new ActiveXObject('Microsoft.XMLHTTP')
    xhr.open('POST', 'ajax.php', true)
    xhr.setRequestHeader('content-type', 'applications/x-www-form-urlencoded')
    xhr.send('sld=testing&tld=com&registrar=namecheap')
  </script>
</head>

ajax.php

var_dump($_POST);    // without these var_dumps
var_dump($_REQUEST); // i receive a 500 error (internal server error)

if ($_SERVER["REQUEST_METHOD"] === "POST"){
  include "includes/connect_to_database.php";
  $pdo = $connection->prepare("INSERT INTO domains (sld, tld, registrar) VALUES (:sld, :tld, :registrar)");
  $pdo->execute(array(
    ":sld" => $_REQUEST["sld"],
    ":tld" => $_REQUEST["tld"],
    ":registrar" => $_REQUEST["registrar"]
  ));
  $connection = null;
}

fwiw: connect_to_database.php

try {
  $connection = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);
  $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully!";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage() . ".";
}

MySQL Table Schema

enter image description here

  • It says the culprit column is sld, so it's as if none of the data is being passed forward.
  • The responseText is also blank.
  • I get the exact same error using $_POST too.
  • Both var_dump($_REQUEST) and var_dump($_POST) return empty arrays in the response.
  • I've tried using encodeURIComponent on the post string, and that didn't work.
  • Notably, I receive a 500 error (internal server error) if I remove the var_dump statements.

Could it be that I'm not sending all of the necessary headers?

What exactly am I doing wrong for the data not to be passed forward?

like image 729
oldboy Avatar asked Apr 15 '26 04:04

oldboy


1 Answers

You are using wrong request header. Change it to

xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')

instead of

applications/x-www-form-urlencoded notice one 's' here.

I think you may not require $_POST and $_REQUEST same time. So you may remove one of them.

like image 163
sagar Avatar answered Apr 17 '26 16:04

sagar