Newbie in back end

I have a project that im doing for school, but im getting this error everytime and also im having some issues using xampp I want to make a register form and a login form and also the website will have a session so when i go to other html files its still getting that im in the same email what i wanted to do is that i have 4 individual files 1. html file : that has the form tag and the name of each input 2. php file : here im just making error handling to send it to js to change style in css 3. js file: im changing the style so that it makes shake effect if for example the confirm_password is wrong 4 css file but the problem im always getting this issue Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON and also i dont why for some reason when i try to save any file i need to be in incognito window after saving a just close and the open another windown and mysql keeps crashing please anyone can help me with this project im so frustrated im trying to self learn but i got no time to do this my deadline is in 3 days
15 Replies
Waddah
Waddah10mo ago
I can provide all files if someone wants to check it out I dont know what im doing ):
Skylark
Skylark10mo ago
If that error is happening in the browser, which I think it is, you’re using JSON.parse() on the PHP file, you said that you’re passing it to JS to style. You just want to handle it as plain text not JSON. In the event that that error is occurring in XAMPP you’re using json_decode() on the HTML file
Waddah
Waddah10mo ago
function checkEmailExists(email) {
// Send an AJAX request to check if the email already exists
fetch('register.php', {
method: 'POST',
body: JSON.stringify({ email: email }),
headers: {
'Content-Type': 'application/json'
},
})
.then(response => response.json()) // Parse JSON response
.then(data => {

if (data.email_exists) {
// Email already exists, display an error message
const errorMessage = document.querySelector('.message');
errorMessage.textContent = 'Email is already registered.';
errorMessage.style.color = "red";
document.querySelector('input[name="email"]').classList.add('shake');
document.querySelector('input[name="email"]').value = "";

setTimeout(function () {
// Restore the original message
document.querySelector('input[name="email"]').classList.remove('shake');
errorMessage.textContent = "Signup now and get full access to our app.";
errorMessage.style.color = "";
}, 2000);
} else if (data.error) {
// Handle other errors if necessary
console.error('Error:', data.error);

} else {
// Email is available, continue with the registration
document.querySelector('.form').submit(); // Submit the form
}
})
.catch(error => {
console.error('Error:', error);
});
}
function checkEmailExists(email) {
// Send an AJAX request to check if the email already exists
fetch('register.php', {
method: 'POST',
body: JSON.stringify({ email: email }),
headers: {
'Content-Type': 'application/json'
},
})
.then(response => response.json()) // Parse JSON response
.then(data => {

if (data.email_exists) {
// Email already exists, display an error message
const errorMessage = document.querySelector('.message');
errorMessage.textContent = 'Email is already registered.';
errorMessage.style.color = "red";
document.querySelector('input[name="email"]').classList.add('shake');
document.querySelector('input[name="email"]').value = "";

setTimeout(function () {
// Restore the original message
document.querySelector('input[name="email"]').classList.remove('shake');
errorMessage.textContent = "Signup now and get full access to our app.";
errorMessage.style.color = "";
}, 2000);
} else if (data.error) {
// Handle other errors if necessary
console.error('Error:', data.error);

} else {
// Email is available, continue with the registration
document.querySelector('.form').submit(); // Submit the form
}
})
.catch(error => {
console.error('Error:', error);
});
}
<?php
session_start();

$host = 'localhost';
$db = 'website';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];

$response = []; // Initialize an empty response array

try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
$response['error'] = $e->getMessage();
echo json_encode($response);
exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$fname = $_POST['first_name'] ?? '';
$lname = $_POST['last_name'] ?? '';
$petname = $_POST['pet_name'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$cpassword = $_POST['confirm_password'] ?? '';

// Validate input and check if passwords match
if (empty($fname) || empty($lname) || empty($email) || empty($password) || empty($cpassword) || $password != $cpassword) {
$response['error'] = 'Invalid input or passwords do not match';
} else {
// Check if the email already exists in the database
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
$stmt->execute([$email]);
$emailExists = (bool)$stmt->fetchColumn();

if ($emailExists) {
// Email already exists, set email_exists to true in the response
$response['email_exists'] = true;
} else {
// Email is available, proceed with insertion
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// File upload handling for pet image
if (isset($_FILES['pimg']) && $_FILES['pimg']['error'] === UPLOAD_ERR_OK) {
$imgData = file_get_contents($_FILES['pimg']['tmp_name']);

$stmt = $pdo->prepare("INSERT INTO users (fname, lname, petname, email, password, pimg) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$fname, $lname, $petname, $email, $hashed_password, $imgData]);

// Set session variable and cookie
$_SESSION['userName'] = $fname;
setcookie('userName', $fname, time() + (86400 * 30), "/"); // Set cookie for 30 days

$response['success'] = 'Registration successful';
} else {
$response['error'] = 'Error in file upload';
}
}
}

// Return the response as JSON
echo json_encode($response);
}
?>
<?php
session_start();

$host = 'localhost';
$db = 'website';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];

$response = []; // Initialize an empty response array

try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
$response['error'] = $e->getMessage();
echo json_encode($response);
exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$fname = $_POST['first_name'] ?? '';
$lname = $_POST['last_name'] ?? '';
$petname = $_POST['pet_name'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$cpassword = $_POST['confirm_password'] ?? '';

// Validate input and check if passwords match
if (empty($fname) || empty($lname) || empty($email) || empty($password) || empty($cpassword) || $password != $cpassword) {
$response['error'] = 'Invalid input or passwords do not match';
} else {
// Check if the email already exists in the database
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
$stmt->execute([$email]);
$emailExists = (bool)$stmt->fetchColumn();

if ($emailExists) {
// Email already exists, set email_exists to true in the response
$response['email_exists'] = true;
} else {
// Email is available, proceed with insertion
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// File upload handling for pet image
if (isset($_FILES['pimg']) && $_FILES['pimg']['error'] === UPLOAD_ERR_OK) {
$imgData = file_get_contents($_FILES['pimg']['tmp_name']);

$stmt = $pdo->prepare("INSERT INTO users (fname, lname, petname, email, password, pimg) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$fname, $lname, $petname, $email, $hashed_password, $imgData]);

// Set session variable and cookie
$_SESSION['userName'] = $fname;
setcookie('userName', $fname, time() + (86400 * 30), "/"); // Set cookie for 30 days

$response['success'] = 'Registration successful';
} else {
$response['error'] = 'Error in file upload';
}
}
}

// Return the response as JSON
echo json_encode($response);
}
?>
Im gonna die please help )::::
Skylark
Skylark10mo ago
Hmm I see You are missing this from your php file, and I've never actually returned JSON without that header to know what the behaviour is. I can't imagine it would then insert doctype but it could
header('Content-Type: application/json; charset=utf-8');
header('Content-Type: application/json; charset=utf-8');
8 more things: 1. Line 22 of your php file you should not include internal error messages. Just return a status 500 and "Internal server error" and then log that error to a file. 2. Salt your passwords. 3. It's possible for profile picture images to fail uploading. 4. Use HttpOnly for your cookies. 5. Don't use first and last names, just ask for a name. You almost never need to know which part is which, and not everyone wants to give you their last name. You can ask for a name, if you are handling shipping that will be done seperately and again you'd just ask for name. Around the world a lot of naming conventions exist that don't fit first and last, such as East Asian countries having the family name first, and Dutch with things like "van der" between names that don't neatly split up. 6. Consider un-nesting your code, you have 4 levels of indentation and a lot of things happening. 7. Avoid long lines, it's harder to read 8. Expand your variable names, there's no point doing fname when you can do the much clearer first_name
Skylark
Skylark10mo ago
Figured I'd make those 9 changes. This code is untested. Just be aware I removed first and last names and replace it with name and username, additionally added a check to make sure usernames were unique
Waddah
Waddah10mo ago
@Skylark Thanks for helping me!
clevermissfox
clevermissfox10mo ago
Btw you can get that shake effect with purely css if if’s invalid
Zoë
Zoë10mo ago
They can steal the shake animation from my pen https://codepen.io/z-/pen/ZEydQPx CSS lines 24-43 with the animation being on line 22. It's very simple
Zed Dash
CodePen
[CPC] Dropdown Slots
It slightly stretches the definition of a dropdown, but it's a single input with a finite number of known valid options, that just require a click to g...
Zoë
Zoë10mo ago
I just read through their JS, it looks like they're already using a CSS animation, they're adding and removing a shake class
clevermissfox
clevermissfox10mo ago
My point was that they could use a pseudo selector to trigger it , :valid or :invalid (not sure where support is for :user-valid :user-invalid yet)
Zoë
Zoë10mo ago
The validity is controlled by the JS
clevermissfox
clevermissfox10mo ago
Zoë
Zoë10mo ago
That's for things like if you have a number input and a value is outside of the range. HTML and CSS don't know that the email is invalid. You can use an input with type email and use :valid for essentially matching *@*, but that doesn't care about if the email is already in use
clevermissfox
clevermissfox10mo ago
I swear I've seen a way to connect it though to the JS so if the regex matches the :user-valid styles apply and if regex doesn't match :user-invalid styles apply.
Want results from more Discord servers?
Add your server