Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Strider64 last won the day on September 2

Strider64 had the most liked content!

About Strider64

  • Birthday 08/28/1964

Contact Methods

  • Website URL

Profile Information

  • Gender
  • Location
    A burb of Detroit, MI

Recent Profile Visitors

10,520 profile views

Strider64's Achievements

Advanced Member

Advanced Member (4/5)




Community Answers

  1. You don't need a registration form/page as all you have to do is hash your password that you want to use. That's what I do when I develop my website(s).
  2. Here's a good website that helped me with composer when I first started out using it. https://devdojo.com/bobbyiliev/use-composer-like-a-pro-the-dependency-manager-for-php It might not help you with this project, but it'll give you a better understanding on how to use it.
  3. You need to do something like this -> // Add an event listener to the edit form's submit event editForm.addEventListener("submit", async function (event) { // Prevent the default form submit behavior event.preventDefault(); // Create a FormData object from the edit form const formData = new FormData(editForm); //console.log("form data", formData); // Send a POST request to the edit_update_blog.php endpoint with the form data const response = await fetch("edit_update_blog.php", { method: "POST", body: formData, }); // Check if the request was successful if (response.ok) { const result = await response.json(); console.log(result); // If the response has a "success" property and its value is true, clear the form if (result.success) { resultInput.value = ''; // Clear the current value of the search input field resultInput.placeholder = "New Search"; // Set the placeholder to `New Search` image_for_edit_record.src = ""; image_for_edit_record.alt = ""; editForm.reset(); // Resetting the edit form searchForm.reset(); // Resetting the search form // Reset select box to default (first) option const selectBox = document.querySelector('select[name="heading"]'); selectBox.selectedIndex = 0; } } else { console.error( "Error submitting the form:", response.status, response.statusText ); // Handle error response } }); also using `console.log` helps in debugging, plus your `sql_connection.php` is expecting back json data back.
  4. Sure, I just do something like this echo "<pre>" . print_r($results, 1) . "</pre>"; It's a great way to debug also.
  5. /* ----- Upload File / Image ----- */ function uploadFile(uid) { const url = 'process.php'; const form = document.querySelector('form'); form.onsubmit = function(e) { e.preventDefault(); const files = document.querySelector('[type=file]').files; const formData = new FormData(); for (let i = 0; i < files.length; i++) { let file = files[i]; formData.append('files[]', file); formData.append('uploadid', uid); } fetch(url, { method: 'POST', body: formData }).then(response => { return response.text(); }).then(data => { console.log(data); }); }; return; } Instead of using the addEventListener method for the form submission, you can directly bind the function to the form's onsubmit?
  6. Personally, if I were writing a chess game I would use JavaScript and Canvas not PHP for the main coding part of the game.
  7. I just wanted to add that when I took a course in web design one of the things to do is keep the form simple as possible. I'm assuming all that data is coming from a form? If that case I would simplify it down a bit as most visitors will leave that website if they see a HTML form that l large. An example of what I'm talking about. <form class="registerStyle" action="register.php" method="post"> <input id="secret" type="hidden" name="user[secret]" value=""> <div id="qr-code-container" class="d-none"> <img id="qr-code-image" src="" alt="QR Code"> <p id="qr-code-info">Scan QR Code for 2FA</p> </div> <div class="first"> <label for="first_name">First Name</label> <input id="first_name" type="text" name="user[first_name]" value="" tabindex="2" required> </div> <div class="last"> <label for="last_name">Last Name</label> <input id="last_name" type="text" name="user[last_name]" value="" tabindex="3" required> </div> <div class="screenName"> <label class="text_username" for="username">Username <span class="error"> is unavailable!</span> </label> <input id="username" class="io_username" type="text" name="user[username]" value="" tabindex="4" required> </div> <div class="telephone"> <label for="phone">Phone (Optional)</label> <input id="phone" type="tel" name="user[phone]" value="" placeholder="555-555-5555" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" tabindex="5"> </div> <div class="emailStyle"> <label class="emailLabel" for="email">Email <span class="emailError"> is invalid</span> </label> <input id="email" type="email" name="user[email]" value="" tabindex="1" autofocus required> </div> <div class="password1"> <label for="passwordBox">Password</label> <input class="passwordBox1" id="passwordBox" type="password" name="user[password]" value="" tabindex="6" required> <label for="passwordVisibility">Show Passwords (private computer)</label> <input class="passwordBtn1" id="passwordVisibility" type="checkbox" tabindex="7"> </div> <div class="password2"> <label for="redoPassword">ReEnter Password</label> <input class="passwordBox2" id="redoPassword" type="password" name="user[comfirm_password]" value="" tabindex="8" required> </div> <div class="birthday"> <label for="birthday">Birthday (optional)</label> <input id="birthday" type="date" name="user[birthday]" value="1970-01-01" tabindex="9"> </div> <div class="submitForm"> <button class="submitBtn" id="submitForm" type="submit" name="submit" value="enter" tabindex="10"> Submit </button> </div> </form> or at least pull the data in easier -> Example: $user = $_POST['user'];
  8. My suggestion is to use composer https://getcomposer.org/ as it will save you a lot a headaches and you don't have to reinvent the wheel. Then you can just do something like the following -> <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/config.php'; require_once "vendor/autoload.php"; // Import the ErrorHandler and Database classes from the PhotoTech namespace. use brainwave\{ ErrorHandler, Database, Links, ImageContentManager, LoginRepository as Login }; // Instantiate the ErrorHandler class $errorHandler = new ErrorHandler(); // Set the exception handler to use the handleException method from the ErrorHandler instance set_exception_handler([$errorHandler, 'handleException']); // Create a new instance of the Database class $database = new Database(); // Create a PDO instance using the Database class's method $pdo = $database->createPDO(); $login = new Login($pdo); if ($login->check_login_token()) { header('location: dashboard.php'); exit(); } $cms = new ImageContentManager($pdo); a sample class -> <?php // ErrorHandler.php namespace brainwave; use PDOException; use Throwable; use JsonException; class ErrorHandler implements ErrorHandlerInterface { public function handleException(Throwable $e): void { if ($e instanceof PDOException) { error_log('PDO Error: ' . $e->getMessage()); } elseif ($e instanceof JsonException) { error_log('JSON Error: ' . $e->getMessage()); } else { error_log('General Error: ' . $e->getMessage()); } } } I would also check out namespace for PHP classes.
  9. This is taken from my website project -> $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); $extensions = array("jpeg", "jpg", "png"); if (in_array($file_ext, $extensions, true) === false) { $errors[] = "extension not allowed, please choose a JPEG or PNG file."; } /* * If no errors save ALL the information to the * database table. */ if (empty($errors) === true) { // Code that does it.... } I know my variable naming isn't exact, but it should give you a basic way in doing it. I have the GitHub repository -> https://github.com/Strider64/brain-wave-blitz/blob/master/create_cms.php feel free to look around.
  10. A simple way in my opinion would to do something like the following. fetch('https://example.com/data-endpoint') // replace with your actual URL .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); // this returns a promise }) .then(data => { console.log(data); // this will log the whole data to the console // you can access any data point like this: console.log(data.newOffers); // logs: null console.log(data.usedOffers[0].price); // logs: 49.23 // if you want to loop through all the usedOffers you can do something like this: data.usedOffers.forEach(offer => { console.log(`Offer ID: ${offer.id}`); console.log(`Price: ${offer.price}`); console.log(`Delivery Rate: ${offer.deliveryRate}`); // ... and so on for other properties }); }) .catch(e => { console.log('There was a problem with the fetch operation: ' + e.message); }); I'm half asleep that from the JavaScript side, but I find JavaScript more flexible than PHP and easier.
  11. They don't have to if you design and develop the website correct.
  12. I do it a little different way - I do all the time figure in JavaScript (I use Vanilla JavaScript) -> "use strict"; // Function to calculate the time remaining till a certain end time const getTimeRemaining = (countdown_date) => { // Parse the end time and current time into milliseconds const endtimeParsed = Date.parse(countdown_date); const nowParsed = Date.parse(new Date()); // Calculate the total remaining time in milliseconds const total = endtimeParsed - nowParsed; // Breakdown the total time into days, hours, minutes, and seconds const seconds = Math.floor((total / 1000) % 60); const minutes = Math.floor((total / 1000 / 60) % 60); const hours = Math.floor((total / (1000 * 60 * 60)) % 24); const days = Math.floor(total / (1000 * 60 * 60 * 24)); // Return a time object that has the total remaining time and the breakdown return { total, days, hours, minutes, seconds }; }; // Function to display a countdown clock on the webpage const myClock = (id, countdown_date) => { // Find the clock and its components by their IDs const clock = document.getElementById(`display_clock${id}`); const daysSpan = clock.querySelector(`.day${id}`); const hoursSpan = clock.querySelector(`.hour${id}`); const minutesSpan = clock.querySelector(`.minute${id}`); const secondsSpan = clock.querySelector(`.second${id}`); // Function to update the clock display const updateClock = () => { // Get the remaining time const time = getTimeRemaining(countdown_date); // Update the display of each component of the clock // padStart() is used to ensure that all components are two digits daysSpan.textContent = time.days; hoursSpan.textContent = String(time.hours).padStart(2, '0'); minutesSpan.textContent = String(time.minutes).padStart(2, '0'); secondsSpan.textContent = String(time.seconds).padStart(2, '0'); // If the total remaining time is zero or less, stop the clock by clearing the interval if (time.total <= 0) { clearInterval(timeInterval); } } // Call updateClock once immediately, then at regular intervals updateClock(); const timeInterval = setInterval(updateClock, 1000); }; function fetchRoutine() { // Define the data you want to send to the server const grabDate = "myDate=endDate"; // Define the options for the fetch call const fetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }, body: grabDate }; // Make the fetch call fetch('countdown_date.php', fetchOptions) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } // If the response was ok, proceed to parse it as JSON return response.json(); }) .then(data => { console.log('data', data); document.getElementById("countdown_date").textContent = data.date_format; document.getElementById("display_title").textContent = data.title; let countdown_date = new Date(Date.parse(data.time_left)); myClock(1, countdown_date); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); } fetchRoutine(); Here's the HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Countdown Clock</title> <link rel="stylesheet" href="reset.css"> <link rel="stylesheet" href="countdown.css"> </head> <body> <div class="info"> <h1 id="display_title"></h1> <h2 id="countdown_date"></h2> </div> <div id="display_clock1"> <figure class="box"> <div class="day1"></div> <figcaption>Days</figcaption> </figure> <figure class="box"> <div class="hour1"></div> <figcaption>Hours</figcaption> </figure> <figure class="box"> <div class="minute1"></div> <figcaption>Minutes</figcaption> </figure> <figure class="box"> <div class="second1"></div> <figcaption>Seconds</figcaption> </figure> </div> <script src="count_down.js"></script> </body> </html> and the css *{ -webkit-box-sizing: border-box; box-sizing: border-box; } div.info { display: block; width: 100%; max-width: 300px; height: auto; text-align: center; padding: 2px; margin: 10px auto; } div.info::after { content: ''; display: block; clear: both; } h1 { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; font-size: 1.2em; line-height: 1.5; } h2 { font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; font-style: italic; font-weight: 300; } div#display_clock1 { display: block; width: 100%; max-width: 190px; height: auto; margin: 5px auto; background-color: pink; } div#display_clock1 figure.box { float: left; display: block; width: 100%; max-width: 40px; height: 70px; color: #fff; text-align: center; padding: 0; margin-left: 5px; } div#display_clock1 figure.box div { background-color: #2e2e2e; height: 50px; line-height: 50px; } div#display_clock1 figure.box figcaption { font-family: Arial, Helvetica, sans-serif; font-size: 0.6em; line-height: 20px; font-weight: bold; color: #000; } it's an old script that I made changes to, so it used a little PHP <?php header('Content-type: application/json'); $endDate = filter_input(INPUT_POST, 'myDate'); if ($endDate === 'endDate') { $count_down_date = new DateTime('2023-07-17 00:00:00', new DateTimeZone("America/Detroit")); $data['time_left'] = $count_down_date->format("Y/m/d H:i:s"); $data['date_format'] = $count_down_date->format("l - F j, Y"); $data['title'] = "Countdown to "; output($data); } function errorOutput($output, $code = 500) { http_response_code($code); echo json_encode($output); } /* * If everything validates OK then send success message to Fetch / JavaScript */ function output($output) { http_response_code(200); echo json_encode($output); } This could be done in JavaScript or even pulling from a Database Table. Like I said it's an old script that I modernized it a little.
  13. There are times that it needs to be done, for example if a game has multiple choices and there are only 2 possible answers. This is a JavaScript pulling data from a database table using fetch -> // This line sets the text content of the button to the corresponding answer (ans1, ans2, ans3, ans4) // with a "📷" character at the beginning. button.textContent = `📷 ${[ans1, ans2, ans3, ans4][index]}` || ""; // If there's no corresponding answer, the button is disabled (its pointer events are set to "none"). // Otherwise, the button is enabled (its pointer events are set to "auto"). if (![ans1, ans2, ans3, ans4][index]) { button.style.pointerEvents = "none"; } else { button.style.pointerEvents = "auto"; } Though I have of admit most of the time is a waste of time coding for empty fields.
  14. if you file is outside the root directory you should use include(__DIR__ . "/../includes/db.php"); $_SERVER['DOCUMENT_ROOT'] returns the root directory defined by the server configuration file
  15. I have been developing an online trivia game for years now and I have finally wrapped this around my head. (Well, at least I think 😂 ) HTML <div id="answers"> <button class="buttonStyle" id="ans1"></button> <button class="buttonStyle" id="ans2"></button> <button class="buttonStyle" id="ans3"></button> <button class="buttonStyle" id="ans4"></button> </div> JavaScript // Function to handle the event when an answer is selected. const pickAnswer = (answerIndex) => { return () => { choice = answerIndex; checkAnswer(); // Only show the next button if the next question exists if (index < triviaData.length - 1) { nextButton.style.display = "block"; // show the next button after an answer is chosen } }; }; // The `startGame` function takes an object as an argument with properties: ans1, ans2, ans3, ans4, id, question. // These properties represent the answers to the current question, the question's id, and the question itself, respectively. const startGame = ({ ans1, ans2, ans3, ans4, id, question }) => { // This line sets the id of the current question to the "data-record" attribute of the element with id "currentQuestion". document.querySelector("#currentQuestion").setAttribute("data-record", id); // This line sets the display number of the current question (index + 1) to the text content of the element with id "currentQuestion". document.querySelector("#currentQuestion").textContent = (index + 1).toString(); // This line sets the text content of the element with id "question" to the question itself. document.querySelector("#question").textContent = question; // This loop iterates over each of the answer buttons. answerButtons.forEach((button, index) => { // This line checks if there was a previous "pickAnswer" event listener attached to the button, // and if so, removes it. const previousPickAnswer = button.__pickAnswer__; if (previousPickAnswer) { button.removeEventListener("click", previousPickAnswer); } // This line creates a new "pickAnswer" event listener, and attaches it to the button. const newPickAnswer = pickAnswer(index + 1); button.addEventListener("click", newPickAnswer, false); button.__pickAnswer__ = newPickAnswer; // This line sets the text content of the button to the corresponding answer (ans1, ans2, ans3, ans4) // with a "📷" character at the beginning. button.textContent = `📷 ${[ans1, ans2, ans3, ans4][index]}` || ""; // If there's no corresponding answer, the button is disabled (its pointer events are set to "none"). // Otherwise, the button is enabled (its pointer events are set to "auto"). if (![ans1, ans2, ans3, ans4][index]) { button.style.pointerEvents = "none"; } else { button.style.pointerEvents = "auto"; } }); }; I comment the script out and I think it's self-explanatory. OK, I'm tired as this is the latest I have stayed up. 🤣
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.