[edit]
Fetch
https://davidwalsh.name/fetch
const form = {
email: document.querySelector("#email"),
password: document.querySelector("#password"),
submit: document.querySelector("#submit"),
messages: document.getElementById("messages"),
};
let button = form.submit.addEventListener("click", (e) => {
e.preventDefault();
const login = "http://berladyn.home/auth/login.inc.php";
fetch(login, {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then(response => {
if (response.data === "Success!"){
alert('You are logged in!');
}
console.log('response: ', response.code, response.status, " - ", response.data);
})
.catch((err) => {
console.log(err);
});
});
document.addEventListener('DOMContentLoaded', function() {
// Password Visibility Toggle
const passwordInput = document.getElementById('password');
const showPasswordCheckbox = document.getElementById('showPassword');
showPasswordCheckbox.addEventListener('change', function() {
if (this.checked) {
passwordInput.type = 'text';
} else {
passwordInput.type = 'password';
}
})
// Simple client-side validation
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (username.length < 5) {
alert('Username must be at least 5 characters long.');
event.preventDefault(); // Prevent the form from submitting
} else if (password.length < 8) {
alert('Password must be at least 8 characters long.');
event.preventDefault(); // Prevent the form from submitting
}
});
});
// Function to fetch data from the PHP script
async function fetchDataFromPHP() {
try {
// The URL points to your PHP script location
const response = await fetch('api.php');
// Check if the request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the response body as JSON
const data = await response.json();
// Log the data to the console or use it in your application
console.log("Data received from PHP:", data);
displayData(data); // Call a function to display the data
} catch (error) {
console.error("Fetch error:", error);
}
}
// Function to display the data (example)
function displayData(data) {
const outputElement = document.getElementById('output');
if (outputElement && data.message) {
outputElement.textContent = `Message: ${data.message}, Status: ${data.status}`;
}
}
// Call the function when the page loads or on a button click
fetchDataFromPHP();
<?php
// Set the content type to application/json
header('Content-Type: application/json');
// PHP data to be returned
$response_data = [
'message' => 'Hello from PHP!',
'status' => 'success',
'timestamp' => time()
];
// Encode the data into a JSON string and echo it
echo json_encode($response_data);
?>