Javaskript Site don’t comunicate with php Backend on API Server

I have 2 Servers. One that serves the Javascript Site to the Client and one that handels the Private Stuff.
The Client should Scan an QR Code an send the Content (something like 044d-9ed1-473c) to the Backend Server. (For Testing 10.1.1.120). If the Backend says true, the page will be green for 200ms and you can scan the next Voucher. Else it will be Red for 400ms. EASY.

Here is my Code. (The PHP worked as it was GET and I only Changed GET to POST)The “API-Server”

<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);

function checkCouponValidity($searchCode, &$codes) {
    foreach ($codes as &$coupon) {
        if ($coupon['Code'] == $searchCode) {
            if ($coupon["valid"] == true){
                $coupon["valid"] = false;
                $coupon["invalid_timestamp"] = date("D, d M Y H:i:s", time());
                return true; // Coupon gefunden und gültig
            }
        }
    }
    return false; // Coupon nicht gefunden oder ungültig
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Annahme: Die JSON-Datei enthält einen Array von Objekten
    $codes = json_decode(file_get_contents("codes.json"), true);

    $requestData = json_decode(file_get_contents('php://input'), true);

    if ($codes !== null && isset($requestData["qrCode"])) {
        $searchCode = $requestData["qrCode"];

        if (checkCouponValidity($searchCode, $codes)) {
            // Jetzt kannst du $codes zurück in die JSON-Datei schreiben
            file_put_contents("codes.json", json_encode($codes, JSON_PRETTY_PRINT));
            echo json_encode(array("isValid" => true));
        } else {
            echo json_encode(array("isValid" => false));
        }
    } else {
        echo json_encode(array("error" => "Fehler beim Verarbeiten der Anfrage."));
    }
} else {
    echo json_encode(array("error" => "Ungültige Anfragemethode."));
}
?>

And Here for my Frontend:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Code Scanner</title>
    <link rel="stylesheet" href="style.css">
</head>
<body id="body">

<video id="qr-video" width="100%" height="100%"></video>
<div id="qr-result"></div>

<script src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        let scanner = new Instascan.Scanner({
            video: document.getElementById('qr-video'),
            mirror: false, // Füge diese Option hinzu, um die Spiegelung der Kamera zu deaktivieren
            facingMode: 'environment' // Füge diese Option hinzu, um die Kamera auf der Rückseite des Geräts zu verwenden
        });

        scanner.addListener('scan', function (content) {
            // Hier kannst du die gescannten Daten verwenden und eine Anfrage an deinen API-Server senden
            checkQRCodeValidity(content);
        });

        Instascan.Camera.getCameras().then(function (cameras) {
            if (cameras.length > 0) {
                scanner.start(cameras[1]); // Ändere die Indexnummer entsprechend der verfügbaren Kameras
            } else {
                console.error('No cameras found.');
            }
        }).catch(function (e) {
            console.error(e);
        });
    });

    function checkQRCodeValidity(qrCodeContent) {
        // Hier sollte die Logik für die Überprüfung des QR-Codes auf dem Server implementiert werden
        // Du kannst eine Ajax-Anfrage verwenden, um die Überprüfung durchzuführen
        // Beispiel mit Fetch-API:
        fetch('http://10.1.1.120/codeCheck/v1/index.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ qrCode: qrCodeContent }),
        })
            .then(response => response.json())
            .then(data => {
                // Hier kannst du die Antwort des Servers verarbeiten
                document.getElementById('qr-result').innerText = data.isValid ? validCode() : inValideCode();
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('qr-result').innerText = 'Fehler bei der Überprüfung des QR-Codes';
                inValideCode();
            });
    }

    function validCode(){
        document.getElementById("body").style.backgroundColor = "green"
        navigator.vibrate(200)
        setTimeout(reset, 200)
    }
    function inValideCode(){
        document.getElementById("body").style.backgroundColor = "red"
        navigator.vibrate(400)
        setTimeout(reset,400)
    }
    function reset(){
        document.getElementById("body").style.backgroundColor = "blue"
    }
</script>
</body>
</html>

I got an error, but can’t really debug it on mobile. I got an Browser like Eruda to see the console, JavaScript only says Type error. So I ask ChatGPT and yeeeeeees…. 2h later I’m got not a single step forward. It convinced me to rewrite my Code from easy GET to POST idk. The Big World Wide Web don#t rescued me. I made it on booth sides and now I’m Stuck I have no Clue what to do.

I think its an really easy error and its my blindheit.

<3 Thank you!

When would you choose to use Java to code a multiplayer web game?

I want to code a multiplayer card game that users can play over the web, sort of like https://skribbl.io/. I would think it’d be simplest to just use React to design frontend and code all the logic with Javascript but I’ve also heard Java is the best language to create games. Would it be a good idea/possible to code the game in Java and then host it using React and Node? I do want to learn to use Java more but is this not the best use for it.

Changing countdown time [duplicate]

I’m trying to add 10 hours to this countdown code below. It’s counting down to midnight 01/30 local time but I need it to be 10 hours after that. So 10am on 01/30. Any idea how I would specify this in the below code? Many thanks!

(function () {
  const second = 1000,
        minute = second * 60,
        hour = minute * 60,
        day = hour * 24;

  let today = new Date(),
      dd = String(today.getDate()).padStart(2, "0"),
      mm = String(today.getMonth() + 1).padStart(2, "0"),
      yyyy = today.getFullYear(),
      nextYear = yyyy,
      dayMonth = "01/30/",
      birthday = dayMonth + yyyy;
  
  today = mm + "/" + dd + "/" + yyyy;
  if (today > birthday) {
    birthday = dayMonth + nextYear;
  }
  //end
  
  const countDown = new Date(birthday).getTime(),
      x = setInterval(function() {    

        const now = new Date().getTime(),
              distance = countDown - now;

        document.getElementById("days").innerText = Math.floor(distance / (day)),
          document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
          document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
          document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);

        //do something later when date is reached
        if (distance < 0) {
          document.getElementById("headline").innerText = "";
          document.getElementById("countdown").style.display = "none";
          document.getElementById("content").style.display = "block";
          clearInterval(x);
        }
        //seconds
      }, 0)
  }());    

Why is this javascript ressetting the values for this rows in this 3d array every time I update it

    const batchIndex = Math.floor(x / 30);
    const newX = x % 30;
    const innerMap = [...state.map[batchIndex][newX]];


    innerMap[newX] = thing;
    console.log(state.map[batchIndex]); // this shows the right value
    state.map[batchIndex] = [...state.map[batchIndex]];
    // This shows the previously right value reset to zero for some reason
    console.log(state.map[batchIndex]);


    state.map[batchIndex][z] = [...innerMap];

Anytime I add a row it clears out the previous rows. This doesn’t happen for columns.

How can I make the floor panel appear on top of a 3D shape? I’m using 3JS

I am working on a 3JS project and need help making the floor panel appear on top of a 3D shape. I have tried various methods, but the floor panel either disappears or is hidden behind the 3D shape.

Here’s what I have done so far. Basically I am using screenshot of map-tile right now and then drawing a
3D irregular polygon shape By using extrude geometry on map tile.This is what I’ve done so far

so I want that to bring the piece of floor which is behind the 3D shape come top of the 3D shape like this.
This is what I want to achieve

what does export {default} from ‘@some-package’ means

The current project I’ve started working on follows some weird way of exporting things which I’ve never came across before.

I’ve a File A and a file B, File A has a bunch of exports and

File A:

export * from "./lib/types";
export * as messages from "./locale/messages";
export { getInitialProps } from "./lib/get-initial-props";

File B:

export { default } from "fileA";

I don’t see anything exported as default from file A, so what’s the default value we’re destructuring and exporting from file B. Also I don’t see any import statements in File B, is the import implied ? And is this a good approach of exporting and importing things?

I am getting a supabaseURL is required and I do not know why in astro

I feel like I’m missing something. Doing something wrong. Maybe missing an await somewhere or an async? (I did try looking in the post of someone having the same problem with svelte but I couldnt find a workable answer. i did move the .env to the top level of the directory struct, still didnt work.

@supabase/supabase-js is installed

errors I get when I run npm run dev

[ERROR] supabaseUrl is required.

my .env file ( i did install dotenv)

SUPABASE_URL=<I know this is where i put my https url>
SUPABASE_ANON_KEY= <I Know the anon key goes here.>

my supabaseClient.jsx (or should this be js and not jsx?)

import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.SUPABASE_URL
const supabaseKey = process.env.SUPABASE_ANON_KEY
const supabase = createClient(supabaseUrl, supabaseKey)
export default supabase

in my index.astro

import supabase from '../config/supabaseClient';

io.ReadAll error if adding a single character into a js script in html file

The problem:
i’m trying to create a messenger with golang. So, learning jQuery & AJAX for data updating without refreshing the page. I wrote a function to get data from textbox(js script sends POST to a golang server). Everything works ok until i add any js script in html file.

Golang function code:

func read_msgbox(w http.ResponseWriter, r *http.Request) string {
    var msg string
    defer r.Body.Close()
    body, err := io.ReadAll(r.Body)
    if err != nil {

        log.Println("error catching submition", err)
        return ""
    }
    msg = string(body)

    return msg
}

Html + go templates file:

<!doctype html>
<html lang='en'>
    <head>
        <meta charset="utf-8">
        <title>Best messenger</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <main>
            <h2><a href="/">Messenger</a></h2>
            <h3>Chat with {{.Name}} </h3> 
            <p>Your message: 
                <form action="" name="msgboxform" id="msgboxform" method="post">
                    <input type="text" name="msgbox" id="msgbox"> 
                </form>
                <script src="/static/JS/post_submit.js"></script>
            </p>
            </div>
            <link href="/static/CSS/message_style.css" rel="stylesheet" type="text/css">
            <p>
                Messages:
                <br>
                {{range .Msgs}}
                <div class = "box">
                    <div class = "text">
                        {{.Text}}
                    </div>
                    <div class="name-time">
                        <div class = "name">
                            {{.Sender_name}}
                        </div>
                        <div class="time">
                            {{.Time}}
                        </div>
                    </div>
                </div>
                {{end}}  
            </p>
        </main>
    </body>
    <script>
        function doSmth(){
        /*if i add smth there io.ReadAll errs "http: invalid Read on closed Body"
        unnecessary code, comment or spaces. Doesn't matter where in code the script is
        nothing happens if there are 3 spaces, but errs if i add 4th lmao */
        }
    </script>
    
</html>

post_submit.js:

const msgboxForm = document.getElementById("msgboxform")
msgboxForm.addEventListener("submit", function(e){
    e.preventDefault();
    let msg = new FormData(e.target).get("msgbox");
    document.getElementById("msgboxform").reset();
    $.ajax({
        url : window.location.href,
        type : 'POST',
        data : msg,
        connection : close,
        success : function(){
            console.log(msg);
        }
    });
});

Suppose this is because code somehow tries to read a request body before a response but idk what should i do with this.
I tried some staff with “Connection: close” in js AJAX submittion but looks like it doesn’t solve the problem.

Also the message logs into a js console but there are something with go application that breaks.

Firebase Authentication API with php

<?php

class FirebaseOTPAuthentication {
    private $firebaseConfig;

    public function __construct($config) {
        $this->firebaseConfig = $config;
        $this->initializeFirebase();
        add_shortcode('firebase_otp_authentication', array($this, 'renderHTML'));
    }

    private function initializeFirebase() {
        $firebaseVersion = '8.10.0'; // Adjust the version as needed
    
        wp_enqueue_script('firebase-app', "https://www.gstatic.com/firebasejs/{$firebaseVersion}/firebase-app.js", array(), null, true);
        wp_enqueue_script('firebase-auth', "https://www.gstatic.com/firebasejs/{$firebaseVersion}/firebase-auth.js", array('firebase-app'), null, true);
    
        wp_add_inline_script('firebase-app', 'var firebaseConfig = ' . json_encode($this->firebaseConfig) . '; firebase.initializeApp(firebaseConfig);', 'after');
    }
    
    

    public function renderHTML() {
        ob_start();
        ?>
        <h1>Firebase OTP Authentication</h1>
        <input type="text" id="phoneNumber" placeholder="Enter your phone number">
        <button onclick="sendOTP()">Send OTP</button>
        <input type="text" id="verificationCode" placeholder="Enter OTP">
        <button onclick="verifyOTP()">Verify OTP</button>
        <div id="recaptcha-container"></div> <!-- Add this line for Recaptcha container -->
        <script>
            var firebaseConfig = <?php echo json_encode($this->firebaseConfig); ?>;

            function sendOTP() {
                var phoneNumber = document.getElementById("phoneNumber").value;
                var appVerifier = new firebase.auth.RecaptchaVerifier("recaptcha-container");

                firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
                    .then(function (confirmationResult) {
                        window.confirmationResult = confirmationResult;
                    })
                    .catch(function (error) {
                        console.error("Error sending OTP: ", error);
                    });
            }

            function verifyOTP() {
                var verificationCode = document.getElementById("verificationCode").value;
                confirmationResult.confirm(verificationCode)
                    .then(function (result) {
                        console.log("User signed in: ", result.user);
                    })
                    .catch(function (error) {
                        console.error("Error verifying OTP: ", error);
                    });
            }
        </script>
        <?php
        return ob_get_clean();
    }
}

// Firebase configuration
$firebaseConfig = [
    "apiKey" => "",
    "authDomain" => "",
    "projectId" => "",
    "storageBucket" => "",
    "messagingSenderId" => "",
    "appId" => ""
];

// Instantiate the class
$firebaseAuth = new FirebaseOTPAuthentication($firebaseConfig);

I am working on custom wordpress plugin…

In this, problem is when I use firebase cdn version 8.10.0 then work ok but when I use latest version 10.7.2 or any version other after 8.10.0 then this not work and give error in console

Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-auth.js:1:1)
Uncaught ReferenceError: firebase is not defined
at test2/:386:277
Uncaught SyntaxError: Unexpected token ‘export’ (at firebase-app.js:2539:1)

Please suggest some solution…is this version problem or some other problem?

How do I have a toggle that uses localstorage? [duplicate]

let SleepSwitch = document.getElementById("SleepSwitch");

function ToggleSleep() {
    let canSleep = localStorage.getItem('canSleep');
    //alert(canSleep);
    if (canSleep) {
        localStorage.setItem('canSleep', false);
    } else if (!canSleep) {
        localStorage.setItem('canSleep', true);
    }
    canSleep = localStorage.getItem('canSleep');
    alert(canSleep);
}

Note: The issue is not with the sleepswitch. HTML is included for reference

<label class="switch">
    <input type="checkbox" id="SleepSwitch" onchange="ToggleSleep()">
    <span class="slider round"></span>
</label>

I have already tried for an hour or 2, and can’t figure it out

Price Calculator: Update Total Price when Guest Qty and/ or Selection changes (JS & HTML)

I am building a price calculator for a tour. The total price should change based on the tour type selected and based on the number of guests.

Right now the calculator updates and calculates the total price when a tour type is selected, however I can’t get it to update when I change the guest count.

The way it programed right now, if I put in guest count first an then select a tour type, the total price displays correctly. However, if I then go back and try to update the guest count, the price won’t update – so I currently have to change the guest count, then select a new tour type and then reselect the tour type that I want, in order to get an updated total

function populate(tournameId) {
  var total = 0;
  var quantity = document.getElementsByName('quantity')[0].value;
  var tournameSelect = document.getElementById(tournameId);

  let selectedOption = tournameSelect.options[tournameSelect.selectedIndex];

  var selectedtournameValue = +selectedOption.dataset.price;
  var total = quantity * selectedtournameValue;
  document.getElementById("total").value = total;
}
<p class="normalinput">Enter Total Number of Guests:</p>
<input type="number" class="quantity" name="quantity" value="0" required>
<br>
<select class="normalinput" name="tourname" id="tourname" onchange="populate('tourname')">
  <option data-price="0" value="None">None</option>
  <option data-price="59" value="G0001">Milano Coffee Crawl (Coffee Included) <span>&#8364;       </span>59</option>
  <option data-price="49" value="G0002">Milano Coffee Crawl (Coffee Not Included) <span>&#8364;</span>49</option>
  <option data-price="39" value="G0003">Milano History Walk <span>&#8364;</span>39</option>
  <option data-price="69" value="G0004">Napoli Coffee Crawl (Coffee Included) <span>&#8364;</span>69</option>
  <option data-price="59" value="G0005">Npoli Coffee Crawl (Coffee Not Included) <span>&#8364;</span>59</option>
</select>
<p class="total"> Total: <span>&#8364;</span><input type="text" name="total" id="total" value="0"></p>

ajax code for retriving data from db is correct still cant display the specific result which is searched for on the page

my project is a todolist website. in which I have added a search page where a task can be searched . task with day date time will be display, the code for that seems correct to my knowledge but it just displays the whole list instead of what user wants to searches for
this is the ajax code:

type function showSearchResults() {
        
        // Use AJAX to submit the form asynchronously
        var form = document.getElementById("searchForm");
        var formData = new FormData(form);

        var xhr = new XMLHttpRequest();
        xhr.open("GET", form.action + "?" + new URLSearchParams(formData).toString(), true);
        xhr.onload = function () {
            console.log('Search Results Received:', xhr.responseText);
            document.getElementById("searchResults").style.display = "block";
            document.getElementById("allHistory").style.display = "none";
        };
        xhr.send();
    }

    function showAllHistory() {
        
        // Use AJAX to submit the form asynchronously
        var form = document.getElementById("allHistoryForm");
        var formData = new FormData(form);

        var xhr = new XMLHttpRequest();
        xhr.open("GET", form.action + "?" + new URLSearchParams(formData).toString(), true);
        xhr.onload = function () {
            console.log('All History Received:', xhr.responseText);
            document.getElementById("allHistory").style.display = "block";
            document.getElementById("searchResults").style.display = "none";
        };
        xhr.send();
    }here

I inspected it in the developers tool to see if it is getting the right data. i found it is succesfully getting the right data. but for some unknown reason it always displays the whole list of data no matter what user will search for
this is a screenshot from developer tool
[(https://i.stack.imgur.com/CadpQ.png)]
please help

How to resolve: ‘default’ (reexported as ‘SyntheticPlatformEmitter’) was not found in ‘./SyntheticPlatformEmitter’?

I have a react native expo app. And I recently upgraded to the newest packages.

But now when I start the app with expo start. And I choose w for web. I get this errors

web compiled with 1 error and 1 warning
Web Bundling failed 317ms
[object Object]
WARNING in ./node_modules/expo-modules-core/build/index.js:14
export 'default' (reexported as 'SyntheticPlatformEmitter') was not found in './SyntheticPlatformEmitter' (module has no exports)
  12 | export { default as deprecate } from './deprecate';
  13 |
> 14 | export {
  15 |   DeviceEventEmitter,
  16 |   EventEmitter,
  17 |   NativeModulesProxy,

This is my package.json file:

{
  "name": "dierenwelzijnapp",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start:production": "NODE_ENV=production npx expo export:web .env.production --openssl-legacy-provider, react-app-rewired start react-scripts start",
    "start:development": "NODE_ENV=development expo start --openssl-legacy-provider, react-app-rewired start react-scripts start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "lint": "eslint . --ext .js",
    "postinstall": "patch-package",
    "build": "react-scripts build",
    "start-webpack": "webpack-dev-server --mode production --open"
  },
  "dependencies": {
    "@ant-design/icons": "4.0.0",
    "@expo-google-fonts/lato": "^0.2.2",
    "@expo-google-fonts/oswald": "^0.2.2",
    "@expo/config": "^8.1.2",
    "@expo/webpack-config": "^0.12.52",
    "@react-native-async-storage/async-storage": "1.18.2",
    "@react-navigation/bottom-tabs": "^6.5.4",
    "@react-navigation/native": "^6.1.3",
    "@react-navigation/stack": "^6.3.14",
    "babel-plugin-styled-components-react-native-web": "^0.2.2",
    "css-to-react-native": "^3.2.0",
    "env-cmd": "^10.1.0",
    "expo": "^44.0.6",
    "expo-font": "~11.4.0",
    "expo-screen-orientation": "~6.0.6",
    "expo-status-bar": "~1.6.0",
    "lottie-react-native": "5.1.6",
    "next-transpile-modules": "^10.0.1",
    "patch-package": "^8.0.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.72.6",
    "react-native-dotenv": "^3.4.9",
    "react-native-gesture-handler": "~2.12.0",
    "react-native-paper": "^5.1.3",
    "react-native-safe-area-context": "4.6.3",
    "react-native-screens": "~3.22.0",
    "react-native-svg": "13.9.0",
    "react-native-web": "~0.19.6",
    "react-native-web-lottie": "^1.4.4",
    "react-toast-notifier": "^1.0.3",
    "styled-components": "^5.3.6",
    "webpack-cli": "^5.1.4",
    "zod": "^3.22.4"
  },
  "parserOptions": {
    "parser": "@babel/eslint-parser",
    "requireConfigFile": false
  },
  "devDependencies": {
    "@babel/core": "^7.19.3",
    "@expo/metro-runtime": "^2.2.12",
    "@react-native-community/eslint-config": "^3.2.0",
    "eslint": "^8.32.0",
    "prettier": "^2.8.3",
    "react-app-rewired": "^2.2.1",
    "react-refresh": "^0.14.0",
    "webpack": "^5.89.0"
  },
  "private": true
}

So I searched for: SyntheticPlatformEmitter. But i cannot finid something related to that pakcage name.

And I deleted the node_modules folder en reinstalled with npm install

Question: How to resolve the error:

Module not found: Can't resolve 'react-native-web/dist/vendor/react-native/NativeEventEmitter/RCTDeviceEventEmitter