Hi guys i have a problem about recaptcha form, for some who doesn’t know it is robot confirmation make sure that user is not a robot. In anyway i get this error when i try to submit the form: SyntaxError: Unexpected token ‘<‘, ”
“… is not valid JSON
Error! Something went wrong. Error message:
i think problem most likely in js and html with form submission but idk how to fix it i am new to recaptcha api, here is my code
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LOGIN</title>
<link rel="icon" type="image/x-icon" href="resources/images/my_dragon_ico.ico">
<script src="js/jquery.js"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="js/login_script.js"></script>
<link rel="stylesheet" type="text/css" href="css/login_style.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<h2>Login</h2>
<form id="login-form" onsubmit="login(event)">
<label for="username">Username or Email:</label>
<input type="text" id="username" name="username" maxlength="60" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" maxlength="60" required>
<label for="showPassword" id="showPasswordLabel" class="show-password" onclick="show_password()"></label><br>
<div class="g-recaptcha" data-sitekey="6LdL2vkpAAAAALwGNJLmDrSWq2BqDbEt3QSdqrK2"></div>
<button type="submit" style="font-family: Arial, sans-serif;">Login</button>
</form>
<div id="response"></div>
</div>
<script>
function changeUrl() {
const url = window.location.href; // Gets the full URL
const baseUrl = window.location.origin; // Gets the base URL (http://localhost:8000)
const pathAfterBaseUrl = url.substring(baseUrl.length); // Gets the path after the base URL
history.pushState({}, pathAfterBaseUrl, '/ ');
// This changes the URL displayed in the address bar to '/new-url'
}
window.onload = function() {
//playSound();
var expectedFrom = "index";
var urlParams = new URLSearchParams(window.location.search);
var from = urlParams.get('from');
if (from !== expectedFrom) {
alert("You must follow the sequence. Redirecting you back...");
window.location.href = expectedFrom + ".html";
}
//changeUrl();
};
function show_password () {
var passwordInput = document.getElementById('password');
var showpassword_css = document.getElementById('showPasswordLabel');
var icon = this;
if (passwordInput.type === 'password') {
passwordInput.type = 'text';
showpassword_css.style.backgroundImage = "url('resources/images/open_eye.png')";
} else {
passwordInput.type = 'password';
showpassword_css.style.backgroundImage = "url('resources/images/closed_eye.png')";
}
}
</script>
</body>
</html>
And JS:
setTimeout(function() {
// Code to be executed after 4000 milliseconds (4 seconds)
console.log('This message is displayed after 4 seconds');
// Your other code here
}, 4000);
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function saveUsernameToTextFile() {
// Wait for 4 seconds before redirecting
await delay(4000);
// Redirect to the new page
window.location.href = 'second_menu_start_login.html?from=index';
}
// Usage example
// saveUsernameToTextFile('exampleUsername');
// Call this function when the user logs in successfully
function handleSuccessfulLogin() {
// Save the username to the text file
//alert("we good here");
saveUsernameToTextFile();
}
function login(event) {
event.preventDefault();
var usernameInput = document.getElementById('username');
var passwordInput = document.getElementById('password');
var usernameOrEmail = usernameInput.value;
var password = passwordInput.value;
var recaptchaResponse = grecaptcha.getResponse();
alert(recaptchaResponse);
var loginData = {
usernameOrEmail: usernameOrEmail,
password: password,
'g-recaptcha-response': recaptchaResponse
};
fetch('php/login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(loginData)
})
.then(response => response.json())
.then(result => {
const responseDiv = document.getElementById('response');
responseDiv.innerHTML = ''; // Clear previous messages
if (result.status === 'success') {
Alert.success('Success! Login successful. Wait 4 seconds before you will move on.', 'Success', { displayDuration: 4000 });
handleSuccessfulLogin();
} else if (result.status === 'error') {
if (result.message === 'Invalid credentials.') {
Alert.error('Error! Login failed. Please check your credentials.', 'Error', { displayDuration: 4000 });
} else if (result.message === 'Error opening file.') {
Alert.error('Error! Login failed. Error with connecting to the database.', 'Error', { displayDuration: 4000 });
} else if (result.message === 'Invalid request method.') {
Alert.error('Error! PHP request failed.', 'Error', { displayDuration: 4000 });
} else if (result.message === 'Confirm you are not robot.') {
Alert.error('Error! Please comfirm you are not a robot.', 'Error', { displayDuration: 4000 });
}
}
})
.catch(error => {
console.error('Error:', error); // Add logging here
Alert.error('Error! Something went wrong. Error message: ', error, 'Error', { displayDuration: 4000 });
});
}
var Alert = undefined;
(function(Alert) {
var alert, error, trash, info, success, warning, _container;
info = function(message, title, options) {
return alert("info", message, title, "fa fa-info-circle", options);
};
warning = function(message, title, options) {
return alert("warning", message, title, "fa fa-warning", options);
};
error = function(message, title, options) {
return alert("error", message, title, "fa fa-exclamation-circle", options);
};
trash = function(message, title, options) {
return alert("trash", message, title, "fa fa-trash-o", options);
};
success = function(message, title, options) {
return alert("success", message, title, "fa fa-check-circle", options);
};
alert = function(type, message, title, icon, options) {
var alertElem, messageElem, titleElem, iconElem, innerElem, _container;
if (typeof options === "undefined") {
options = {};
}
options = $.extend({}, Alert.defaults, options);
if (!_container) {
_container = $("#alerts");
if (_container.length === 0) {
_container = $("<ul>").attr("id", "alerts").appendTo($("body"));
}
}
if (options.width) {
_container.css({
width: options.width
});
}
alertElem = $("<li>").addClass("alert").addClass("alert-" + type);
setTimeout(function() {
alertElem.addClass('open');
}, 1);
if (icon) {
iconElem = $("<i>").addClass(icon);
alertElem.append(iconElem);
}
innerElem = $("<div>").addClass("alert-block");
alertElem.append(innerElem);
if (title) {
titleElem = $("<div>").addClass("alert-title").append(title);
innerElem.append(titleElem);
}
if (message) {
messageElem = $("<div>").addClass("alert-message").append(message);
innerElem.append(messageElem);
}
if (options.displayDuration > 0) {
setTimeout((function() {
leave();
}), options.displayDuration);
} else {
innerElem.append("<em>Click to Dismiss</em>");
}
alertElem.on("click", function() {
leave();
});
function leave() {
alertElem.removeClass('open');
alertElem.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
return alertElem.remove();
});
}
return _container.prepend(alertElem);
};
Alert.defaults = {
width: "",
icon: "",
displayDuration: 4000,
pos: ""
};
Alert.info = info;
Alert.warning = warning;
Alert.error = error;
Alert.trash = trash;
Alert.success = success;
return _container = void 0;
})(Alert || (Alert = {}));
this.Alert = Alert;
Please help me with recaptcha form submission data transfer, i am not sure about this line in js var recaptchaResponse = grecaptcha.getResponse(); i probably get null in this place and data transfer fail.