I am currently trying to create a signup page on XAMPP. The summary of my system is that when user clicks submit button, JS performs xmlhttprequest to a php file via POST that uploads the user's data to database and creates a new account. However, after some debugging, it became clear that the php file seemed to not have received any of the POST data.
my JS:
form.addEventListener("submit", function (ev) {
ev.preventDefault();
xhr = new XMLHttpRequest();
xhr.timeout = 10000;
xhr.open("POST", "/db/signup.php");
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------974767299852498929531610575");
xhr.addEventListener("timeout", function () {
errorMsg("Timed out. Try again later.")
}, false);
xhr.addEventListener("readystatechange",
function () {
if (xhr.readyState == 4) {
if (xhr.status == 200 && xhr.responseText !== null) {
// if (xhr.responseText.startsWith("ERROR: ")) { regular code
// loadingIcon.style.opacity = "0";
// errorMsg(xhr.responseText.slice(6));
// } else {
// location.href = "/?message=Created%20account!";
// }
errorMsg(xhr.responseText); // debugging code
} else {
location.href = "/500.html";
}
}
},
false);
xhr.send(new FormData(form));
}, false);
my PHP:
try {
$statement = $pdo->prepare("INSERT INTO users (name, email, password, birthday, imgpath) VALUES (:n, :e, :p, :dob, :imgpath)");
$statement->execute(
["n" => $_POST["name"], "e" => $_POST["email"],"p" => password_hash($_POST["password"], PASSWORD_BCRYPT), "dob" => $_POST["dob"], "imgpath" => $path ?? ""]);
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) {
$error = "Already an account with email \"" . htmlspecialchars($_POST["email"], ENT_QUOTES | ENT_HTML5) . "\"";
} else {
$error = "An error occured. Try again later.";
}
}
NOTE: These are only parts of my entire code
I hope you can find a solution to my problem. All help is appreciated!
Remove
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------974767299852498929531610575");
from your Javascript code. You don't need to set this manually, XHR will take care of it for you and ensure it's done correctly.