i coun’t get specefic data from a collection from database. I am using MongoDb, Nodejs, Express j

const burqaCollection = client.db('BubrqaDB').collection('burqas');
app.get('/burqas/:id', async(req,res)=>{
  const id = req.params.id;
  const query = {_id : new ObjectId(id)};
  const result = await burqaCollection.findOne(query);
  console.log(result);
  res.send(result);
});

here is my code..Why i could’t get specefic id related data from here? i face similar problem with my another projects. here i try to console.log(id) , i get my id. but if i try to console.log(result), then i get null

why does js file ignore many statements

this is the html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oxford Languages Center</title>
    <link rel="stylesheet" href="Quiz.css">
</head>
<body>
    <main class="main">
        <header class="header">
            <a href="#" class="logo"><img src="logo1.png"></a>
            <nav class="navbar">
                <a href="#" class="active">Oxford Languages Center</a>
            </nav>
        </header>
        <div class="container">
            <section class="quiz-section">
                <div class="quiz-box">
                    <h1 id="pl">Placement Test</h1>
                    <div class="quiz-header">
                        <span id="en">English Test</span>
                        <span class="header-score">Score: 0 / 54</span>
                    </div>



                    <h2 class="question-text">Are you ______?</h2>

                    <div class="option-list">
                        <!--<div class="option">
                            <span>AA</span>
                        </div>
                        <div class="option"></div>
                            <span>BB</span>
                        </div>
                        <div class="option">
                        </div>
                            <span>CC</span>
                        </div>
                        <div class="option"></div>
                            <span>DD</span>
                        </div>-->
                    </div>

                    <div class="quiz-footer">
                        <span class="question-total">1 of 54 Questions </span>
                        <button class="next-btn">Next</button>
                    </div>
                </div>

                <div class="result-box">
                    <h2>Test Result!</h2>
                    <div class="percentage-container">
                        <div class="circular-progress">
                            <span class="progress-value">0%</span>
                        </div>

                        <span class="score-text">Your Score 0 out of 54</span>
                    </div>

                    <div class="buttons">
                        <button class="tryAgain-btn">Try Again</button>
                        <button class="goHome-btn">Go To Home</button>
                    </div>
                </div>
            </section>
        <section class="home">
            <div class="home-content">
                <h1>PLACEMENT TEST</h1>
                <p>English</p>
                <button class="start-btn">Start Test</button>
                <br>
                <button class="start-btn" onclick="location.href='aaaaa.html'">Start Listening</button>

            </div>
        </div>
        </section>
    </main>

    <div class="popup-info">
        <h2>Questions</h2>
        <span class="info">Choose the correct answer</span>

        <div class="btn-group">
            <button class="info-btn exit-btn">Exit Test</button>
            <a href="#" class="info-btn continue-btn">Continue</a>
        </div>
    </div>





    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="questions.js"></script>
</body>
</html>

this is questions.js

let questions = [
    {
        numb: 1,
        question: "Are you ______?",
        answer: "British",
        options: [
            "British",
            "Tunisia",
            "Wales",
            "England"
        ]
    },
    {
        numb: 2,
        question: "Where ______ work?",
        answer: "does your brother",
        options: [
            "do your brother",
            "is your brother",
            "your brother",
            "does your brother"
        ]
    },
    {
        numb: 3,
        question: "They ______ a wonderful concert last week.",
        answer: "saw",
        options: [
            "see",
            "have seen",
            "seeing",
            "saw"
        ]
    },
    {
        numb: 4,
        question: "They were ______ work last Saturday.",
        answer: "at",
        options: [
            "at",
            "on",
            "in",
            "by"
        ]
    },
    {
        numb: 5,
        question: "Does she ______ a lot of hobbies?",
        answer: "have",
        options: [
            "Is",
            "got",
            "has",
            "have"
        ]
    },
    {
        numb: 6,
        question: "11h45 is ______.",
        answer: "quarter to twelve",
        options: [
            "quarter past eleven",
            "half past eleven",
            "quarter to twelve",
            "half fast twelve"
        ]
    },
    {
        numb: 7,
        question: "The Piccadilly bus ______ now.",
        answer: "is leaving",
        options: [
            "leaves",
            "are living",
            "leaving",
            "is leaving"
        ]
    },
    {
        numb: 8,
        question: "Where ______ tonight?",
        answer: "are we going",
        options: [
            "are we going",
            "we go",
            "go we",
            "we going"
        ]
    },
    {
        numb: 9,
        question: "Your room is upstairs ______ the left.",
        answer: "on",
        options: [
            "On",
            "in",
            "near",
            "at"
        ]
    },
    {
        numb: 10,
        question: "What ______ rooms!",
        answer: "an empty",
        options: [
            "an empty",
            "a empty",
            "empty",
            "emptiness"
        ]
    },
    {
        numb: 11,
        question: "This is the ______ skyscraper in the world.",
        answer: "biggest",
        options: [
            "big",
            "bigger",
            "most big",
            "biggest"
        ]
    },
    {
        numb: 12,
        question: "She ______ soda.",
        answer: "often drinks",
        options: [
            "often drinks",
            "often drinking",
            "drinks often",
            "is often drink"
        ]
    },
    {
        numb: 13,
        question: "The girl ______ dad is a scientist is very clever.",
        answer: "whose",
        options: [
            "which",
            "whom",
            "who",
            "whose"
        ]
    },
    {
        numb: 14,
        question: "Miss Johnson is my ______ secretary.",
        answer: "father's",
        options: [
            "father",
            "fathers'",
            "father's",
            "fathers"
        ]
    },
    {
        numb: 15,
        question: "You're British, ______?",
        answer: "aren't you",
        options: [
            "are you",
            "aren't you",
            "you are",
            "you aren't"
        ]
    },
    {
        numb: 16,
        question: "My result is ______ than yours.",
        answer: "better",
        options: [
            "good",
            "better",
            "more good",
            "more better"
        ]
    },
    {
        numb: 17,
        question: "I ______ of a number between 1 and 10. What ______ it be?",
        answer: "am thinking.../...would",
        options: [
            "think.../...does",
            "think.../...would",
            "was thinking.../...will",
            "am thinking.../...could"
        ]
    },
    {
        numb: 18,
        question: "You speak English ______ I do.",
        answer: "as well as",
        options: [
            "as well",
            "good as",
            "as good",
            "as well as"
        ]
    },
    {
        numb: 19,
        question: "Catherine wasn't impressed by either of her ______ behavior.",
        answer: "sister's",
        options: [
            "sister's",
            "sisters",
            "sisters'",
            "sister"
        ]
    },
    {
        numb: 20,
        question: "He met neither John ______ his wife.",
        answer: "nor",
        options: [
            "or",
            "also",
            "nor",
            "and"
        ]
    },
    {
        numb: 21,
        question: "I'm looking forward ______ you.",
        answer: "to seeing",
        options: [
            "to see",
            "to seeing",
            "seeing",
            "see"
        ]
    },
    {
        numb: 22,
        question: "I ______ since Tuesday!",
        answer: "haven't slept",
        options: [
            "slept",
            "has slept",
            "haven't slept",
            "sleep"
        ]
    },
    {
        numb: 23,
        question: "'Eventually' means ______.",
        answer: "Finally",
        options: [
            "Firstly",
            "Actually",
            "Likely",
            "Finally"
        ]
    },
    {
        numb: 24,
        question: "______ her last week?",
        answer: "Did you invite",
        options: [
            "You invited",
            "Did you invited",
            "Do you invite",
            "Did you invite"
        ]
    },
    {
        numb: 25,
        question: "The thief ______ by the police 2 days ago.",
        answer: "was caught",
        options: [
            "caught",
            "was caught",
            "catches",
            "is caught"
        ]
    },
    {
        numb: 26,
        question: "If I ______ you, I would tell him the truth.",
        answer: "were",
        options: [
            "am",
            "was",
            "were",
            "'ll be"
        ]
    },
    {
        numb: 27,
        question: "______ they played very well, the English team lost the match.",
        answer: "Although",
        options: [
            "Although",
            "However",
            "Nevertheless",
            "In spite"
        ]
    },
    {
        numb: 28,
        question: "Stamps have cost 30p ______ the beginning of the year.",
        answer: "since",
        options: [
            "while",
            "since",
            "occasionally",
            "at"
        ]
    },
    {
        numb: 29,
        question: "If I had time, I ______ many things.",
        answer: "would do",
        options: [
            "do",
            "would do",
            "did",
            "'ve done"
        ]
    },
    {
        numb: 30,
        question: "Would you mind ______ the door?",
        answer: "closing",
        options: [
            "close",
            "to close",
            "closing",
            "closed"
        ]
    },
    {
        numb: 31,
        question: "You must ______ dive into shallow water.",
        answer: "never",
        options: [
            "never",
            "always",
            "sometimes",
            "constantly"
        ]
    },
    {
        numb: 32,
        question: "I forbid ______ the house dressed like that.",
        answer: "you to leave",
        options: [
            "you from leaving",
            "you leave",
            "you to leave",
            "to you of leaving"
        ]
    },
    {
        numb: 33,
        question: "The worker ignored his boss and ______.",
        answer: "got fired",
        options: [
            "is getting sacked",
            "got fired",
            "is fired",
            "is getting fired"
        ]
    },
    {
        numb: 34,
        question: "I haven't met her ______ 3 years",
        answer: "for",
        options: [
            "since",
            "ago",
            "for",
            "yet"
        ]
    },
    {
        numb: 35,
        question: "I would be very interested in ______ for that job.",
        answer: "applying",
        options: [
            "entering",
            "applying",
            "working",
            "writing"
        ]
    },
    {
        numb: 36,
        question: "______ someone means contacting him on the phone.",
        answer: "Reaching",
        options: [
            "Finally finding",
            "Putting you through",
            "Reaching",
            "I'm just checking"
        ]
    },
    {
        numb: 37,
        question: "______ please tell your children to stop shouting?",
        answer: "Would you",
        options: [
            "May you",
            "Would you",
            "Ought you",
            "Should you"
        ]
    },
    {
        numb: 38,
        question: "By Thursday, I ______ ten meetings.",
        answer: "will have had",
        options: [
            "have had",
            "will have had",
            "was having",
            "have"
        ]
    },
    {
        numb: 39,
        question: "______, not five but rather ten candidates were screened through telephone interviews.",
        answer: "Actually",
        options: [
            "Considerably",
            "Pleasantly",
            "Actually",
            "Leisurely"
        ]
    },
    {
        numb: 40,
        question: "Once you ______ the secret code, you must not reveal it to anyone.",
        answer: "are given",
        options: [
            "are given",
            "have given",
            "gave",
            "give"
        ]
    },
    {
        numb: 41,
        question: "This piece was composed by Stravinsky and consists ______ three movements.",
        answer: "of",
        options: [
            "to",
            "by",
            "in",
            "of"
        ]
    },
    {
        numb: 42,
        question: "______, business-class tickets on this flight are less expensive than economy fares.",
        answer: "Oddly enough",
        options: [
            "In view of that fact",
            "Oddly enough",
            "By virtue of",
            "Owing to"
        ]
    },
    {
        numb: 43,
        question: "I ______ on time if the bus hadn't been late.",
        answer: "'d have been",
        options: [
            "have been",
            "was",
            "would be",
            "'d have been"
        ]
    },
    {
        numb: 44,
        question: "Why didn't you ______ that you were feeling ill?",
        answer: "mention",
        options: [
            "advise",
            "remark",
            "mention",
            "tell"
        ]
    },
    {
        numb: 45,
        question: "Although our opinions on many things ______, we're good friends.",
        answer: "differ",
        options: [
            "disagree",
            "oppose",
            "differ",
            "divide"
        ]
    },
    {
        numb: 46,
        question: "You must try and hurry up because my patience is ______ out.",
        answer: "running",
        options: [
            "running",
            "pacing",
            "racing",
            "turning"
        ]
    },
    {
        numb: 47,
        question: "I alone am responsible ______ the mischief perpetrated last night.",
        answer: "for",
        options: [
            "to",
            "with",
            "of",
            "for"
        ]
    },
    {
        numb: 48,
        question: "This supermarket is trying to ______ young shoppers by offering fashionable clothes.",
        answer: "attract",
        options: [
            "target",
            "encourage",
            "persuade",
            "attract"
        ]
    },
    {
        numb: 49,
        question: "______ means there are no tickets left.",
        answer: "Sold out",
        options: [
            "Sold out",
            "Front row",
            "Free seats",
            "Window shopping"
        ]
    },
    {
        numb: 50,
        question: "Everyone ______ that gentlemen ______ blondes",
        answer: "says.../...prefer",
        options: [
            "say.../...prefers",
            "say.../...prefer",
            "says.../...prefer",
            "says.../...prefers"
        ]
    },
    {
        numb: 51,
        question: "As so few members had turned up at the meeting, it was decided to ______ it until further notice.",
        answer: "postpone",
        options: [
            "delay",
            "postpone",
            "wait",
            "hold"
        ]
    },
    {
        numb: 52,
        question: "I strongly ______ investing in these shares because you will get a very good reward.",
        answer: "recommend",
        options: [
            "recommend",
            "commend",
            "order",
            "respond"
        ]
    },
    {
        numb: 53,
        question: "I have tried and tried again and no matter what I do it still shows 'error', I just can't ______ what's wrong",
        answer: "figure out",
        options: [
            "look out",
            "figure out",
            "check out",
            "bring out"
        ]
    },
    {
        numb: 54,
        question: "The question is whether it is ______ to sell up all your shares at this stage rather than wait",
        answer: "wise",
        options: [
            "wisdom",
            "wisely",
            "wise",
            "wisest"
        ]
    },
    
];

let questionCount = 0;
let questionNumb = 1;
let userScore = 0;

const startBtn = document.querySelector('.start-btn');
const popupInfo = document.querySelector('.popup-info');
const exitBtn = document.querySelector('.exit-btn');
const main = document.querySelector('.main');
const continueBtn = document.querySelector('.continue-btn');
const quizSection = document.querySelector('.quiz-section');
const quizBox = document.querySelector('.quiz-box');
const resultBox = document.querySelector('.result-box');
const tryAgainBtn = document.querySelector('.tryAgain-btn');
const goHomeBtn = document.querySelector('.goHome-btn');
const nextBtn = document.querySelector('.next-btn');
const optionList = document.querySelector('.option-list');

startBtn.onclick = () => {
    popupInfo.classList.add('active');
    main.classList.add('active');
}

exitBtn.onclick = () => {
    popupInfo.classList.remove('active');
    main.classList.remove('active');
}

continueBtn.onclick = () => {
    quizSection.classList.add('active');
    popupInfo.classList.remove('active');
    main.classList.remove('active');
    quizBox.classList.add('active');

    showQuestions(questionCount);
    questionCounter(questionNumb);
    headerScore();
}

tryAgainBtn.onclick = () => {
    quizBox.classList.add('active');
    nextBtn.classList.remove('active');
    resultBox.classList.remove('active');

    questionCount = 0;
    questionNumb = 1;
    userScore = 0;
    showQuestions(questionCount);
    questionCounter(questionNumb);
    headerScore();
}

goHomeBtn.onclick = () => {
    quizSection.classList.remove('active');
    nextBtn.classList.remove('active');
    resultBox.classList.remove('active');

    questionCount = 0;
    questionNumb = 1;
    userScore = 0;
    showQuestions(questionCount);
    questionCounter(questionNumb);
}

nextBtn.onclick = () => {
    if (questionCount < questions.length - 1) {
        questionCount++;
        showQuestions(questionCount);
        questionNumb++;
        questionCounter(questionNumb);
        nextBtn.classList.remove('active');
    } else {
        showResultBox();
        console.log("ok");
    }
}

function showQuestions(index) {
    const questionText = document.querySelector('.question-text');
    questionText.textContent = `${questions[index].numb}. ${questions[index].question}`;

    let optionTag = '';
    questions[index].options.forEach((option, i) => {
        optionTag += `<div class="option" onclick="optionSelected(this)"><span>${option}</span></div>`;
    });
    optionList.innerHTML = optionTag;
}

function optionSelected(answer) {
    const userAnswer = answer.textContent.trim();
    const correctAnswer = questions[questionCount].answer;

    if (userAnswer === correctAnswer) {
        answer.classList.add('correct');
        userScore++;
        headerScore();
        nextBtn.classList.add('active');
    } else {
        answer.classList.add('incorrect');

        // Auto select the correct answer
        [...optionList.children].forEach(option => {
            if (option.textContent.trim() === correctAnswer) {
                option.classList.add('correct');
            }
            option.classList.add('disabled');
        });

        nextBtn.classList.add('active');
    }
}

function questionCounter(index) {
    const questionTotal = document.querySelector('.question-total');
    questionTotal.textContent = `${index} of ${questions.length} Questions`
}

function headerScore() {
    const headerScoreText = document.querySelector('.header-score');
    headerScoreText.textContent = `Score: ${userScore} / ${questions.length}`;
}

function showResultBox() {
    quizBox.classList.remove('active');
    resultBox.classList.add('active');

    const scoreText = document.querySelector('.score-text');
    scoreText.textContent = `Your Score ${userScore} out of ${questions.length}`;

    const circularProgress = document.querySelector('.circular-progress');
    const progressValue = document.querySelector('.progress-value');
    let progressStartValue = -1;
    const progressEndValue = (userScore / questions.length) * 100;
    const speed = 20;

    const progress = setInterval(() => {
        progressStartValue++;
        
        progressValue.textContent = `${progressStartValue}%`;
        circularProgress.style.background = `conic-gradient(#c40094 ${ progressStartValue * 3.6}deg, rgba(255, 255, 255, .1) 0deg)`;
        
        if (progressStartValue >= progressEndValue) {
            clearInterval(progress);
        }
    }, speed);
    const data = new FormData();
    data.append('userScore', userScore);
    
    fetch('update_score.php', {
        method: 'POST',
        body: data
    })
    .then(response => response.text())
    .then(result => {
        console.log(result); // Display the response from the PHP script
    })
    .catch(error => console.error('Error:', error));
}

this is update_score.php :

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection parameters
$servername = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "englishquizox"; 

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL to create the scores_table
$sql = "CREATE TABLE IF NOT EXISTS scores_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tel VARCHAR(15) NOT NULL,
    score INT NOT NULL,
    FOREIGN KEY (tel) REFERENCES login_table(tel) ON DELETE CASCADE
)";
$conn->query($sql); // Create table without checking success here for simplicity

// Check if the user is logged in and the session variable exists
if (isset($_SESSION['tel'])) {
    $tel = $_SESSION['tel'];
    if (isset($_POST['userScore'])) {
        $userScore = intval($_POST['userScore']); // Sanitize the score input
        $sql = "INSERT INTO scores_table (tel, score) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $tel, $userScore); 
        if ($stmt->execute()) {
            echo "Score updated successfully.";
        } else {
            echo "Error updating score: " . $stmt->error;
        }
        $stmt->close();
    } else {
        echo "No score received.";
    }
} else {
    echo "User is not logged in.";
}

$conn->close();
?>

ignore the 56 questions classes, I want to send the score to a php file to insert it into a mysql table and the js file doesn’t seem to work fully like if i put some console.log statements the browser ignores them and deos everything else

WebView Flutter – Changing Date/Time closes application

Currently using webview_flutter package to exhibit a custom html page inside my application. It consists of come input forms that are in hh:mm format.
I have attributed default values to all fields, however when changing the values of any hour field the application closes and I get the following error:


I/mple.dive_calc2(11766): Compiler allocated 4206KB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
D/CompatChangeReporter(11766): Compat change id reported: 170233598; UID 10198; state: ENABLED
D/AndroidRuntime(11766): Shutting down VM
E/AndroidRuntime(11766): FATAL EXCEPTION: main
E/AndroidRuntime(11766): Process: com.example.dive_calc2, PID: 11766
E/AndroidRuntime(11766): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.EditText.hasFocus()' on a null object reference

I am using the default implementation of webview and the page loads correctly and runs other scripts correctly, however whenever I change the hour or the minutes inside the fields the application closes.

This is the only function that read those fields, I have also tried commenting it but it still closes my application:

// Function to calculate the time difference in hours and minutes between two fields
async function calculateTimeDifference(startInputId, endInputId) {
    const startTime = await document.getElementById(startInputId).value;
    const endTime = await document.getElementById(endInputId).value;

    // Check if the values are available
    if (startTime && endTime) {
        const startDate = new Date(`1970-01-01T${startTime}:00`);
        const endDate = new Date(`1970-01-01T${endTime}:00`);

        // Calculate the total difference in minutes
        const totalMinutes = Math.abs((endDate - startDate) / 60000);

        // Convert total minutes into hours and minutes
        const hours = Math.floor(totalMinutes / 60);
        const minutes = totalMinutes % 60;

        // Display the result in the console (or it can be used to generate a logbook)
        console.log(`Time difference between ${startInputId} and ${endInputId}: ${hours} hours and ${minutes} minutes`);

        // Return the formatted time (can be used in a PDF or logbook)
        return { hours, minutes };
    } else {
        console.log(`One or both fields (${startInputId}, ${endInputId}) are empty.`);
        return null;
    }
}

When the html loads inside the application it gets the 12h(AM/PM) format by default even though the android emulator is set to be 24h.

Currently using macOS.

Some things I have tried:

  1. Removing the function that reads the hh:mm fields.
  2. Hosting the page in the web
  3. Only running the function with onPageFinished:

Script Tag Not Executing Inside Shopify App Embed Block

I’m developing a Shopify App Embed Block to display a list of recommended products. The H1 tag (“Recommended Products”) is successfully displayed on the page, but the product list is not rendered because the JavaScript code inside the <script> tag is not executed. Here’s my code:

<div id="custom-product-list" class="product-list">
  <!-- Products will be injected here by JavaScript -->
  <h1>Recommended Products</h1>
</div>

<script>
  // Mock products array (this can be fetched via AJAX instead)
  export const products = [
    {
      _id: '1',
      title: 'product 1',
      description: 'Lorem ipsum product 1 dummy description.',
      price: 100,
      compare_at_price: 80,
      featured_image: 'https://images.pexels.com/photos/985635/pexels-photo-985635.jpeg',
      url: 'https://images.pexels.com/photos/985635/pexels-photo-985635.jpeg',
    },
    {
      _id: '2',
      title: 'product 2',
      description: 'Lorem ipsum product 2 dummy description.',
      price: 200,
      featured_image: 'https://images.pexels.com/photos/147641/pexels-photo-147641.jpeg',
      url: 'https://images.pexels.com/photos/147641/pexels-photo-147641.jpeg',
    }
  ];

  function renderProducts(productList) {
    const productContainer = document.getElementById('custom-product-list');
    productContainer.innerHTML = '';

    productList.forEach((product) => {
      const productItem = `
        <div class="product-item">
          <a href="${product.url}">
            <img src="${product.featured_image}" alt="${product.title}">
          </a>
          <h3><a href="${product.url}">${product.title}</a></h3>
          <p class="price">
            ${product.compare_at_price > product.price
              ? `<span class="sale-price">$${product.price}</span>
                 <span class="original-price">$${product.compare_at_price}</span>`
              : `<span class="regular-price">$${product.price}</span>`}
          </p>
        </div>
      `;
      productContainer.insertAdjacentHTML('beforeend', productItem);
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    renderProducts(products);
  });
</script>

{% schema %}
{
  "name": "Custom Product List",
  "target": "section",
  "settings": [
    {
      "type": "number",
      "id": "product_limit",
      "label": "Number of Products",
      "default": 5
    }
  ]
}
{% endschema %}

The H1 tag appears on the page, but the script responsible for rendering the products does not run. This code is inside a Shopify Liquid template file for an App Embed Block.

Why is the JavaScript not executing in this Shopify App Embed Block, and how can I make sure the script is executed to display the product list?

How do I migrate Auth0 rules to actions

I am currently trying to migrate our Auth0 rule to actions. When I take a simple rule that successfully adds a custom role to the token and migrate it to an action the role doesnt show up in the token.

Rule

function (user, context, callback) { if (context.clientName === 'MyClientName') {
  var namespace = 'https://ournamespace.com/';
  var roles = [];

roles.push('testRole');

if (context.accessToken) {  
  context.accessToken[namespace + 'email'] = user.email;
  context.accessToken[namespace + 'scopes'] = roles.join(' ');
}
  
  try {
    user.team_scopes = roles.join(' ');
  } catch (e) {
    console.log(e);
  }
  
  callback(null, user, context);
} else { callback(null, user, context); } }

Result

{
  "name": "My Name",
  "email": "[email protected]",
  "team_scopes": "testRole",
  "iss": "****",
  "sub": "****",
  "aud": "****",
  "iat": ****,
  "exp": ****
}

Action

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://ournamespace.com/';
  let roles = [];
  roles.push('TestRole');
  console.log(`Adding roles to token: ${roles.join(' ')}`);
  api.accessToken.setCustomClaim(`${namespace}team_scopes`, roles.join(' '));
};

Result

{
  "name": "My Name",
  "email": "[email protected]",
  "iss": "****",
  "sub": "****",
  "aud": "****",
  "iat": ****,
  "exp": ****
}

I’ve tried disabling the rule so only the action is there.
The rule and action are named the same.
it almost seems like the action isnt being triggered because when I run it from the Auth0 UI and I seem to get the expected result.

Please help me understand what I’m doing wrong.

Save data submitted from a Form into a Store in Sveltekit

So I’ve got the following component working so far records/new/+page.svelte:

<script>
    import RecordForm from "../../../components/forms/RecordForm.svelte";
    import TrackForm from "../../../components/forms/TrackForm.svelte";
    import { enhance } from '$app/forms';

    export let data;
    export let form;

</script>

<RecordForm mode="new" formData={ {...data, ...form} } />

the above works more as a wrapper, the actual action happens in the RecordForm.svelte component:

<script>
export let mode="new";
export let formData;
</script>

<form method="POST" class="pt-10">
   <!-- a bunch of fields -->
<input
                        name="title"
                        id="title"
                        type="text"
                        value={ formData?.data?.title || "" }
                        class="input input-bordered input-lg w-full max-w-xs"/>

                <label for="title" class="label">
                    {#if formData?.errors?.title}
                        <span class="label-text-alt text-error">{ formData?.errors?.title[0]}</span>
                    {/if}
                </label>

   <div class="flex flex-row pt-10">
                <button type="submit" name="save-and-exit" class="btn btn-primary btn-lg">{ mode == "new" ? "Save and Exit" : "Update and Exit" }</button>
            </div>
</form>

For simplicity, I’ve left out all the fields involved in the form (including only one to showcase the structure of the inputs).
This form has it’s associated action in new/+page.server.js:

export const actions = {
    default: async ({ request, fetch }) => {

        // create API instance
        const recordAPI = new RecordAPI(fetch);

        // retrieve the data from the form
        const data = Object.fromEntries(await request.formData());

        // validate data and create DTO
        const record = recordDTO(data);

        // if errors returned from building the DTO (validation errors) then return the object.
        if (record?.errors && !emptyObject(record.errors)) {
            return {
                "data": record.data,
                "errors": record.errors,
            };
        }

        // save the data
        const response = await recordAPI.post(record);

        if (response.status == 200) {
            throw redirect(302, '/records')
        }

        return {
            data: record,
            "errors": response.errors,
        }

    }
}

So far so good, everything works as expected when the form is submitted.

I want to expand this functionality, and I want to add tracks to a given record. But I want to do this as part of the Record creation process but in a different page/component.

My initial thought is to have 2 buttons on the new Record page. One if the user wants to save the info as it is (without adding the tracks) and another one labeled Tracks that will redirect the user to a page where the tracks for a record can be added.

When the Tracks button is clicked, then we shouldn’t submit the form but save the data into a store, and redirect the user to the Tracks page. Once there the user adds a bunch of tracks and click on Save, at that point the tracks and the record data are merge and send to the backend for processing.

I want to save the record data in a store in case the user wants to go back to the Record page and update some data, so the info is put back in place.

The issue is that I cannot save data into a store from an action in sveltekit, so it has to be done in the client side.

I tried adding the button to the form:

 <div class="flex flex-row pt-10">
                <button type="button" on:click={submitForm} name="add-tracks" class="btn btn-primary btn-lg">{ "-> Tracks" }</button>
            </div>

and retrieve the data from the form in order to save it into the store:

const submitForm = (event) => {
      const data = new FormData(event.currentTarget);
      console.log("FORM DATA", data)
      return
    }

since the data is managed by the formData obj I also tried:

 const submitForm = (event) => {
      event.preventDefault();
      console.log("form data", formData)

      return

but this is not working. Nothing is being printed out.

Any ideas on how to approach this?

custom contact form google sheet

i tryed this code its almost working. but there is an issue with this code.

whats not working

without uploading file the send button not working.

trying to acheive

all input field should have required(name,email,phone,message).
but uploading file must be optional field.

Addditiional : i tryed to add feature like auto sending email to receiver after user submit form successfully. but i unable to code that part,if someone know how to do that is most welcome to add this auto email feature.

here is code i tryed [ (code.gs), (index.html), (library id) ]

library id

 1CcBYkrGSeBRgphHUE92vWInyULOcJ1Ub6eFUR0_gI1h9I6whLjXtDA-P

code.gs

function doGet() {
  return HtmlService.createTemplateFromFile('index').evaluate()
  .addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}

var url = 'google sheet url here'
var sh = 'sheet1'<!-- current google sheet name here -->
var folderId = 'google drive folder id here'

function processForm(formdata){
  var superscript = SuperScript.initSuper(url,sh)
  
  var formObject = {}
  formdata.forEach(element => formObject[element.name] = element.value),
  formdata.forEach(element => formObject[element.message] = element.value)
  formdata.forEach(element => formObject[element.email] = element.value)
  formdata.forEach(element => formObject[element.phone] = element.value)

  var file = superscript.uploadFile(folderId,formObject.myfile.data,formObject.myfilename)
  var ss= SpreadsheetApp.openByUrl(url);
  var ws=ss.getSheets()[0]
   ws.appendRow([
     new Date(),
    formObject.name,
    "'"+formObject.message,
    formObject.email,
    formObject.phone,
    file.getUrl()
  ]);
  };

index.html

<!DOCTYPE html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
        integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  
  
</head>
<body>
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-5 col-md-8 mx-auto shadow border bg-white p-4 rounded">
                <nav class="navbar navbar-dark bg-primary">
                    <a class="navbar-brand" href="#" fw-bold mb-3>WRITE YOUR QUERY / Message</a>
                </nav>
                <br>
                <form id="myForm" onsubmit="handleFormSubmit()">
                    <div id="form_alerts"></div>
                    <div class="form-group mb-3">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" placeholder="Enter your Name here|" name="name"required>
            </div>

            <div class="form-group mb-3">
            <label for="email" >Email</label>
                        <input type="email"  class="form-control" id="email"
            placeholder="Enter your email address here|" name="email" required>
            </div>

            <div class="form-group mb-3">
           <label for="phone">phone number</label><br><br>
  <input type="tel" id="phone" class="form-control" name="phone" placeholder="Enter your phone number here with country code." pattern="[+]{1}[0-9]{2}[0-9]{10}" required><br><br>
  <small>Format: +919234567898</small><br><br>
            </div>

            <div class="form-group mb-3">
              <label for="message">Message</label>
    <textarea class="form-control" id="message" placeholder="Write your message here|" name="message" required ></textarea>
              </div>

                         <div class="form-group mb-3">
                            <label for="uploadFile">Upload File</label>
                            <input type="file" class="form-control" File="file" id="file">
                            </div>
                            <button type="submit" class= "btn btn-primary btn-block">SEND</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
  <script>
        function preventFormSubmit() {
                var forms = document.querySelectorAll('form');
                for (var i = 0; i < forms.length; i++) {
                    forms[i].addEventListener('submit', function (event) {
                        event.preventDefault();
                    });
                }
            }
            window.addEventListener('load', preventFormSubmit);
            function handleFormSubmit() {
                var formdata = $('#myForm').serializeArray()
                formdata.push({
                  name: 'myfile',
                  value: myfile
                })
                google.script.run.withSuccessHandler(success).processForm(formdata);
            }
            function success(){
                 document.getElementById("myForm").reset()
                 Swal.fire({
                  position: 'center',
                  icon: 'success',
                  title: 'sended sucessfully be ready we will contact you shortly',
                  showConfirmButton: true,
      
                })
            }
        var myfile ={},file, reader = new FileReader();
      reader.onloadend = function(e) {
          myfile.data = e.target.result
          myfile.name = file.name
          console.log(myfile)
      };
     $('#file').change(function(){
       file = $('#file')[0].files[0]
        reader.readAsDataURL(file);
     })
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="sweetalert2.all.min.js"></script>
</body>
</html>

Turbo causes full refresh when adding JS per page

According to the Turbo documentation here: https://turbo.hotwired.dev/handbook/building#working-with-script-elements adding JS files into a page’s <head> that are not present on the current page should cause a Turbo to merge the <head> and load the code. Quoting the documentation:

When you navigate to a new page, Turbo Drive looks for any
elements in the new page’s which aren’t present on the current
page. Then it appends them to the current where they’re loaded
and evaluated by the browser. You can use this to load additional
JavaScript files on-demand.

We add these files in the views like:

<%= content_for :head do %>
  <%= javascript_include_tag 'example', 'data-turbo-track': 'reload' %>
<% end %>

However when doing this Turbo always does a full page refresh. This seems to conflict with what the documentation says around merging the heads and loading the files as needed. We have this approach in a lot of our views which makes Turbo almost pointless as it means the page is being fully reloaded between views. The fingerprints of the files are the same so in theory it shouldn’t be doing a full re-load (it doesn’t need to load new JS)

Node.js Express app not rendering HTML file; only shows a blank page

Body: I am developing a simple Node.js application using Express. My goal is to serve an HTML file located in the views folder, but when I access the page, it shows a blank screen without any content.

Code:

const express = require('express');
const path = require('path');

const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'views', 'index.html'));
});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});

HTML File (views/index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Page</title>
</head>
<body>
    <h1>Hello World!</h1>
    <p>This is a test page.</p>
</body>
</html>

Error Messages: I do not see any error messages in the terminal or the browser console.

What I’ve Tried:

I ensured that the server is running and that I can access http://localhost:3000/.
I checked the file paths to ensure they are correct.
I tried using a simple HTML file to see if it renders anything.
I am using Windows 10 (Crack Version) and wondering if it might affect the application.
Expected vs. Actual Behavior:

Expected: The browser should display “Hello World!” and the text “This is a test page.”
Actual: The page is blank with no content displayed.
Environment:

OS: Windows 10 (Crack Version)
Node.js version: 20.17.0
Express version: 4.21.1

Firefox not being helpful by reloading iframe

I want a web page to periodically check for some condition by connecting to a server.
If the condition occurs, it should post a notice, and play a sound.

In order to play the sound, there has to be some user interaction, so I ask the user
to click the page to get the whole thing going, which I call launching.

In order to repeatedly check for the condition, I need to refresh the page.
But that would require the user to click again (repeatedly), so I use an
iframe and refresh that. And it works.

However … in Firefox (only, apparently), if I refresh the parent page itself
(for whatever reason), then Firefox “helpfully” reloads the iframe automatically,
and does the launch right away. Then the sound doesn’t play.

I’m looking to avoid having to remember to do
a hard refresh on the parent page, or remembering to click after I do a soft
refresh, and haven’t found one. Chrome browser doesn’t do this, but I prefer
using Firefox.

Here is what I’ve tried, which isn’t working.

<script>
var launched = false;
function launch()
{
 console.log("Launching: launched = " + launched);
 if (!launched)
   {
    document.getElementById("framex").src = "checkalive1.shtml";
    launched = true;
   }
}
function virginstate()
{
 console.log("virginstate called with launched = " + launched);
 document.getElementById("framex").src = "";
 launched = false;
}
</script>

<body onload="virginstate()" onclick="launch()">
<iframe id="framex" src=""> </iframe>
</body>

and in the browser console:

virginstate called with launched = false

Autoplay is only allowed when approved by the user, 
the site is activated by the user, or media is muted.


checkalive1.shtml:168:7 Uncaught (in promise) DOMException: 
The play method is not allowed by the user agent or the platform 
in the current context, possibly because the user denied permission.

Trying to access a specific route but its getting redirected on / home route after deployement on Vercel [duplicate]

I have three routes in React: ‘/’, ‘/login’, and ‘/edit-user’, where the login route is public, and the other two are protected. I’ve created a protected layout component and an authentication handler in React. The authentication handler checks the uid and sets it in session storage. Based on that, we update the isAuthenticated state.

Everything works fine locally, but after deployment, when isAuthenticated is true, and I try to access any private route, it redirects me to the / (home) route.

App.tsx

import { useState } from "react";
import Home from "./pages/Home";
import Auth from "./pages/Auth";
import ProtectedLayout from "./routes/ProtectedLayout";
import AuthenticationHandler from "./components/Auth/AuthenticationHandler";
import Onboarding from "./pages/Onboarding";

const App: React.FC = () => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
  return (
    <Router>
      {/* Handle authentication within the Router context */}
      <AuthenticationHandler setIsAuthenticated={setIsAuthenticated} />

      <Routes>
        {/* Public Route */}
        <Route path="/login" element={<Auth />} />
          
        {/* Protected Layout */}
        <Route element={<ProtectedLayout isAuthenticated={isAuthenticated} />}>
          <Route path="/" element={<Home />} />
          <Route path="/edit-user" element={<Onboarding />} />
        </Route>
      </Routes>
    </Router>
  );
};

export default App;

ProtectedLayout.tsx


interface ProtectedLayoutProps {
  isAuthenticated: boolean | null;
}

const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({ isAuthenticated }) => {
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return (
    <div>
      <Outlet />
    </div>
  );
};

export default ProtectedLayout;

AuthenticationHandler.tsx

import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

interface Props {
  setIsAuthenticated: (authState: boolean) => void;
}

const AuthenticationHandler: React.FC<Props> = ({ setIsAuthenticated }) => {
  const navigate = useNavigate();

  useEffect(() => {
    const checkAuthentication = () => {
      const urlParams = new URLSearchParams(window.location.search);
      const bbuid = urlParams.get("bbuid");

      if (bbuid) {
        sessionStorage.setItem("bbuid", bbuid);

        navigate(window.location.pathname, { replace: true });

        setIsAuthenticated(true);
      } else if (sessionStorage.getItem("bbuid")) {
        setIsAuthenticated(true);
        
        if (window.location.pathname === "/login") {
          navigate("/", { replace: true });
}      } else {
        setIsAuthenticated(false);
      }
    };

    checkAuthentication();
  }, [navigate, setIsAuthenticated]);

  return null; 
};

export default AuthenticationHandler;

How can I resolve this

Why is my function not writing the data onto my firebase realtime database

Firebase createUserWithEmailAndPassword Works but set() to Realtime Database Fails
I have a Firebase project where I need to register a user using Firebase Authentication, then immediately write the user’s data to the Firebase Realtime Database.

Here’s the structure of my registration function:


export function registerbtn(register, emailinput, passwordinput) {
    register.preventDefault();
    console.log(passwordinput, emailinput);
    const email = emailinput.value;
    const password = passwordinput.value;

    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            // Signed up
            const user = userCredential.user;
            writeUserData(user);  // Writing user data to Firebase DB
            const provider = "local";
            getUserDetails(user);
            saveUserdetails(user, provider);

            window.alert(email + password);
            window.location.href = accountredirect;
            return user;

        })
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(errorMessage + errorCode);
            document.getElementById('error-text').innerHTML = errorCode;
        });
}

I also have a writeUserData function that writes the newly registered user’s data to Firebase Realtime Database:


function writeUserData(user) {
    const userId = user.uid;
    const info = "value";

    // Update the user's data in the database
    const db = getDatabase();
    set(ref(db, 'users/' + userId), {
        username: info,
        email: info,
        profile_picture: info
    })
    .then(() => {
        console.log("User data updated successfully!");
    })
    .catch((error) => {
        console.error("Error updating user data: ", error);
    });
}

The Issue:
Everything inside the registerbtn function works fine, except for the writeUserData function. It doesn’t write to the database, and the console logs show no errors related to Firebase database. However, if I call the writeUserData function separately or outside of the registration process, it works perfectly and writes the data to Firebase.

I’ve tried putting the writeUserData function inside and outside the .then() block, and even exporting/importing it, but the issue persists.

My Firebase Configuration:


import {
    initializeApp
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-app.js";


import {
    getAuth, signOut, signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, createUserWithEmailAndPassword, onAuthStateChanged
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-auth.js";


import {
    getAnalytics
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-analytics.js";


import {
    getDatabase, onValue, child, ref, set, get
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-database.js";


// TODO: Add SDKs for Firebase products that you want to use

// https://firebase.google.com/docs/web/setup#available-libraries


// Your web app's Firebase configuration

// For Firebase JS SDK v7.20.0 and later, measurementId is optional

const firebaseConfig = {

    apiKey: "AIza**************",

    authDomain: "wespot-website.firebaseapp.com",

    databaseURL: "https://wespot-website-default-rtdb.europe-west1.firebasedatabase.app",

    projectId: "wespot-website",

    storageBucket: "wespot-website.appspot.com",

    messagingSenderId: "864768589048",

    appId: "1:864768589048:web:f76790c9abfa6b2e594f0d",

    measurementId: "G-0ZD710W4YE"

};


// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const database = getDatabase();
const auth = getAuth();
export const provider = new GoogleAuthProvider();
const accountredirect = "../index.html";

Steps I’ve Tried:
Logging the user object: To ensure the user object is populated, I added console logs, and it shows the correct user UID.

Firebase Rules: I’ve checked my Firebase Realtime Database rules and made sure they allow authenticated users to write.

Firebase Authentication works fine and the user is successfully created.
Database writes only fail when the writeUserData function is called right after the user registration.
There are no errors in the console, making it hard to trace the issue.
Question:
Why is writeUserData(user) failing when called after createUserWithEmailAndPassword but works perfectly fine when called separately? Could it be a timing issue, or am I missing something else?

Any help or insight would be appreciated!

AgGrid angular scrollbarWidth only applying to the horizontal scroller

AgGrid has a parameter called scrollbarWidth which I can pass into the grid as a number. I was hoping it would alter the width of both the horizontal and vertical scrollbars but it only seems to affect the horizontal scroll width. The vertical scroller seems to stay the same

<ag-grid-angular
  #agGrid
  style="width: 400px; height: 400px;"
  id="myGrid"
  class="ag-theme-balham"
  [columnDefs]="columnDefs"
  [defaultColDef]="defaultColDef"
  [rowData]="rowData"
  (gridReady)="onGridReady($event)"
  [scrollbarWidth]="8"
>
</ag-grid-angular>

My goal was to change the scroller width for both horizontal and vertical and get both of them same width.

Tried my best to create a demo of the issue I have.

Help is much appreciated, Thanks