Skip to content
Advertisement

Submitting a Form with Post method to a PHP passes one of the variables as NULL while it should be a string [closed]

I’m submitting a Form with Ajax. The Form is passed to a PHP server (currently on localhost), which inputs the values into the MySQL database. The problem was that it didn’t pass one variable, and MySQL isn’t accepted NULL.

Anyway, the problem is this part of the code:

let advM = document.getElementById("advertsM");
var mailme = (advM.checked) ? "Yes":"No"; 

Well, to be fair, when I looked at it with Dev Tools (F12), the value of the variable was either “Yes” or “No”.

Additionally, when I looked at the XHR code with F12 tools for submitting the form via Ajax, the variable (mailme) was again either a “Yes” or a “No”.

xhr3.send   (
    "HOTSPOT_NAME="+encodeURIComponent(hsname)+
    "&HTTP_USER_AGENT="+encodeURIComponent(useragent)+
    "&HTTP_ACCEPT_LANGUAGE="+encodeURIComponent(acceptedla)+
    "&FIRST_NAME="+encodeURIComponent(firstname)+
    "&EMAIL="+encodeURIComponent(useremail)+
    "&LANGUAGE="+encodeURIComponent(langua)+
    "&LINK_ORIG="+encodeURIComponent(linkorig)+
    "&MAILING_LIST"+encodeURIComponent(mailme) //mailme has a value of "Yes"/"No"
);

BUT, when nothing was submitting to the MySQL database and I checked the php error logs I came across this error:

PHP Fatal error:  Uncaught mysqli_sql_exception: Column 'MAILING_LIST' cannot be null in C:xampphtdocsHSDBinsert.php:32
Stack trace:
#0 C:xampphtdocsHSDBinsert.php(32): mysqli_stmt->execute()
#1 {main}
  thrown in C:xampphtdocsHSDBinsert.php on line 32

PHP code:

$stmt = $DB->prepare("INSERT INTO users 
    (HOTSPOT_NAME, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, 
    FIRST_NAME, EMAIL, LANGUAGE, 
    LINK_ORIG, MAILING_LIST) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

$stmt->bind_param("ssssssss", $_POST['HOTSPOT_NAME'], 
    $_POST['HTTP_USER_AGENT'], $_POST['HTTP_ACCEPT_LANGUAGE'], 
    $cleaner_fname, $cleaner_email, 
    $_POST['LANGUAGE'], $_POST['LINK_ORIG'], $_POST['MAILING_LIST']);

$stmt->execute(); //line 32
$stmt->close();

What I can’t understand is, why does it pass on NULL when it should clearly be a string (as I put in the breakpoints and verified that the value is a string…)

Any help would be welcome, as I don’t know how to resolve this problem.

Thank you

Advertisement

Answer

I think you may have forgotten an = symbol after &MAILING_LIST in your xhr code:

xhr3.send   (
    ...
    "&MAILING_LIST"+encodeURIComponent(mailme)
);

In addition, if your field only accepts “yes” and “no”, you could set the field default value for “no”, for instance (well, if you can edit the db).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement