I'm trying to set up a website where anyone can access it after filling out a form. I already set up the form with a few fields but my question is how can I use a JS cookie to check if the user has already submitted this form, if it has redirect them to the next page, if not wait until they submit the form and then redirect?
The data from the form does not need to be saved yet, this will be implemented later.
Desired functionality: User opens website, if they have submitted the form before, they just go straight to index page, if they are a new user who has not submitted the form, they fill it out, submit, and are redirected to the index page. Cookie expires in 6 months.
My code that doesn't seem to be working:
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 30 * 60 * 60 * 1000);
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("filled_form");
if (user != "") {
window.location.replace("https://google.com/");
}
}
</script>
</head>
<body onload="checkCookie()">
<form id="form">
<label for="fname">First name:</label><br />
<input type="text" id="fname" name="fname" value="" /><br />
<label for="lname">Last name:</label><br />
<input type="text" id="lname" name="lname" value="" /><br /><br />
<input type="submit" value="Submit" id="submit-button" />
</form>
<script>
const form = document.getElementById("form");
form.addEventListener("submit", function (e) {
e.preventDefault()
setCookie("filled_form", true, 60);
});
</script>
</body>
</html>