what is agile explain all details?

what is agile, why used agile?
why are you using agile process, when exposed this concept , please answer that using question
what is agile, why used agile?
why are you using agile process, when exposed this concept , please answer that using question
what is agile, why used agile?
why are you using agile process, when exposed this concept , please answer that using question
what is agile, why used agile?
why are you using agile process, when exposed this concept , please answer that using question
what is agile, why used agile?
why are you using agile process, when exposed this concept , please answer that using question
what is agile, why used agile?
why are you using agile process, when exposed this concept , please answer that using question

Microsoft Edge Has A BUG! – JS Returns WRONG value on Back Arrow

After clicking the back arrow in Microsoft Edge, my JavaScript runs once again. But there’s a BIG problem!

The values returned by “getElementById(“options”).value” are NOT the correct values for the option that is visible from the dropdown selection.

Firefox and Safari don’t have this problem, so why is Microsoft Edge and Chrome still Buggy after all these years? And therefore how can I overcome this mismatch between the returned getElementById().value and the visibly selected option?

Why does this matter? Because I’m sending dropdown selected values to the server-side via AJAX for an ecommerce shopping cart, and so the returned value needs to match the visible selection for the given dropdown before being sent over.

Naturally customers will occasionally click on the back arrow, and when they do, various values don’t always match with the visible selection – the exact mismatch depends on the particular browser.

So, after detecting that the page has been landed on by the user having clicked the back arrow, I then simply call getElementById().value for all of the dropdowns on the page, pass the values to the server via AJAX, and then use the newly calculated values that are returned by AJAX to refresh the page – a solution that works perfectly for Firefox and Safari, but NOT for Edge and Chrome.

Therefore, I’ve created a small test program that demonstrates the problem perfectly. You’ll notice that I’ve included the code (two HTML files), and a 33 second video which shows the test program running, with Edge on the left and Firefox on the right.

As shown in the video, the steps to reproduce the issue are as follows…

  1. Select option 2
  2. Navigate to page 2 by clicking the link
  3. Click the back arrow

Here’s the video: https://youtu.be/J3tLFXjPDdA

Can you see the problem? within window.onload, getElementById(“options”).value returns “option-1” after clicking back arrow, which does NOT match the selected option “Option 2” that is visible.

Bizarrely, I then discovered that just by delaying the call to getElementById() by setting setTimeout(), the value returned then becomes “option-2” which IS Correct, even for a delay value of 0.

I don’t want to simply reload the page on back arrow as a fix. I’d much rather learn why this mismatch of visible selection vs returned value is happening? If you think this is technically NOT a BUG, then please, I’d love to hear your explanation!

To run the test program, for each of the two pages simply copy the code into a text file and change the extension to .htm, and then right click on …page-1.htm and select open with Edge.

<!DOCTYPE html>

<label for="options">Select Option</label>
<select id="options">
  <option value="option-1">Option 1</option>
  <option value="option-2">Option 2</option>
</select>

<a href="back-arrow-issue-page-2.htm">Page 2</a>

<script>
  window.onpageshow = function(event) // testing for bfcache
  {
    if (event.persisted)
      alert("From bfcache");
  };

  window.onunload = function(){}; // disables bfcache in Firefox when running an htm file from a local drive, so that the script will run for a second time, i.e. after clicking back arrow. Note: this doesn't disable bfcache when running a local htm file in Safari

  window.onload = function()
  {
    console.log("in: window.onload");
    let performance_entries = performance.getEntriesByType("navigation");

    for (var i = 0; i < performance_entries.length; ++i)
    {
      console.log(performance_entries[i].type);

      if (performance_entries[i].type == "back_forward")
      {
        console.log(document.getElementById("options").value);
        setTimeout(delay_test, 0); // 1 worked, and so I then tried 0 which also works
      }
    }
    function delay_test()
    {
      console.log(document.getElementById("options").value);
    }
  }
</script>
<!DOCTYPE html>

<a href="back-arrow-issue-page-1.htm">Page 1</a>

Cheers, Gary.

How can I get past this cors error with nextjs?

I am hitting my backend with no issues in localhost until I use the productions server, then I’m hitting a cors error. I’m using a nextjs backend and vite/react frontend. Any help is appreciated. Thanks in advance

The project structure

backend
   middleware 
      cors.js
   pages
      api
        create-checkout-session.js
   .env.local
src
   routes
      Checkout.jsx
   .env.local

Here is my relevant code

backend/middleware/cors.js

import Cors from 'cors';

const allowedOrigins = [
  process.env.NEXT_PUBLIC_FRONTEND_URL.replace(//+$/, ''),
  process.env.LOCAL_FRONTEND_URL.replace(//+$/, '')
];

const corsMiddleware = Cors({
  methods: ['GET', 'HEAD', 'POST', 'OPTIONS'],
  origin: (origin, callback) => {
    if (!origin || origin === 'null') {
      callback(null, true); // Allow requests with null origin (e.g., localhost file:// requests)
      return;
    }
    const normalizedOrigin = origin.replace(//+$/, '');
    if (allowedOrigins.includes(normalizedOrigin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
});

function runMiddleware(req, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result);
      }
      return resolve(result);
    });
  });
}

export default corsMiddleware;
export { runMiddleware };

backend/pages/api/create-checkout-session.js

import { runMiddleware } from '../../middleware/cors';
import corsMiddleware from '../../middleware/cors';
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {
  await runMiddleware(req, res, corsMiddleware);

  if (req.method === 'OPTIONS') {
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin || 'null');
    res.status(200).end();
    return;
  }

  if (req.method === 'POST') {
    const { amount, originUrl } = req.body;

    try {
      const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [{
          price_data: {
            currency: 'usd',
            product_data: {
              name: 'Total Amount',
            },
            unit_amount: amount,
          },
          quantity: 1,
        }],
        mode: 'payment',
        success_url: `${process.env.NEXT_PUBLIC_FRONTEND_URL}/success`,
        cancel_url: originUrl,
      });

      res.setHeader('Access-Control-Allow-Origin', req.headers.origin || 'null');
      res.status(200).json({ id: session.id });
    } catch (error) {
      res.status(500).json({ statusCode: 500, message: error.message });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end('Method Not Allowed');
  }
}

# .env.local(backend)

STRIPE_SECRET_KEY=sk_test_*****************
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_***************
NEXT_PUBLIC_API_URL=https://api.lotus-dev.net
LOCAL_API_URL=http://localhost:3000

NEXT_PUBLIC_FRONTEND_URL=https://celebritymolds.com
LOCAL_FRONTEND_URL=http://localhost:5173

FRONTEND

the function firing the checkout

  const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLIC_KEY);      

  const handleProceedToCheckout = async () => {
  setLoading(true);
  const stripe = await stripePromise;
  const totalAmount = cart.reduce((sum, product) => sum + product.price * product.quantity, 0) + 30;

  const body = {
    amount: Math.round(totalAmount * 100), // Stripe expects amount in cents
    originUrl: window.location.href,
  };

  const headers = {
    'Content-Type': 'application/json',
  };

  const apiUrl = import.meta.env.MODE === 'development'
    ? import.meta.env.VITE_LOCAL_API_URL
    : import.meta.env.VITE_API_URL;

  try {
    const response = await fetch(`${apiUrl}/api/create-checkout-session`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body),
    });

    console.log('Response:', response); // Inspect the response

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const session = await response.json();

    const result = await stripe.redirectToCheckout({
      sessionId: session.id,
    });

    if (result.error) {
      console.error('Error redirecting to checkout:', result.error.message);
    }
  } catch (error) {
    console.error('Error creating checkout session:', error);
  } finally {
    setLoading(false);
  }
};

# .env.local(frontend)

VITE_STRIPE_PUBLIC_KEY=pk_test_***********
VITE_API_URL=https://api.lotus-dev.net
VITE_LOCAL_API_URL=http://localhost:3000

VITE_FRONTEND_URL=https://celebritymolds.com
VITE_LOCAL_FRONTEND_URL=http://localhost:5173

Using IntersectionObserver to detect scrolling below a target – and keeping it until next target comes into view

Using IntersectionObserver – is it possible to detect scroll intersecting AND past/below every entry – until the next entry comes is scrolled into view (other elements are between the entries.)?

In the example below, I would like to detect scrolling below every element with the class .title, and keep it until the next element with the class .title appears.

I tried with the below, but it doesnt’t work as expected.

Hope my questions makes sense. 🙂

let options = {
    root: null,
    rootMargin: '-50px 0px -50px 0px',
    threshold: [.5]
}

let sectionObserver = new IntersectionObserver((entries, options) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting && window.scrollY >= entry.boundingClientRect.top) {
            // Do something here when scrolling below this entry - until next entry is in view.
            console.log(entry.target);
        }
    });
});

document.querySelectorAll('.title').forEach((section) => {
    sectionObserver.observe(section);
});
<div class="container">
  <div class="title">Title one</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title two</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title three</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title four</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor. Donec ut
    ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros. Aenean
    ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices, consectetur
    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tempus sem. Nulla et leo diam.
  </p>
  <div class="title">Title five</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus dolor id ullamcorper tempor.`enter code here`
    Donec ut ullamcorper tellus. Etiam vel rhoncus urna. Aenean augue nulla, congue a orci at, imperdiet vehicula eros.
    Aenean ornare nibh ut leo faucibus fringilla. Quisque varius ut ipsum egestas feugiat. Mauris id nisl ultrices,
    consectetur

    mauris in, consectetur mi. Sed sit amet dolor urna. Nullam nec enim gravida, pulvinar lacus ut, volutpat nibh.
    Quisque commodo eu tortor ac dictum. Vivamus sodales risus sed blandit vulputate. Proin elit erat, varius non
    tincidunt ut, semper sed erat. Nulla vehicula vitae nisl nec dignissim. Curabitur viverra risus eu est pellentesque
    lobortis. Nullam egestas semper convallis.

    Ut ac blandit risus, sit amet elementum ex. Donec rhoncus augue eu cursus consequat. Duis a sapien sit amet elit
    aliquet molestie. Mauris nec ligula viverra, ornare dolor vel, malesuada nisl. Proin gravida dolor justo, sit amet
    tempus justo consectetur ut. Aenean malesuada iaculis tortor ac varius. Phasellus ultrices purus nisi, eu rutrum
    felis bibendum id. Phasellus enim dui, ultrices sed massa vel, euismod bibendum eros. Duis quis auctor augue, eget
    pellentesque velit. In a est at neque dignissim pellentesque et tem

    pus sem. Nulla et leo diam.
  </p>
</div>

Can’t link javascript file to HTML

I am working on a new computer and refreshing coding. I’m having some trouble linking my script.js file to the index.html. I’ve tried everything and can’t figure out what the problem is.

I have checked for typos and have placed the script file in different areas of the code.
enter image description here

show video after completing gravity form

I have a page with a button. When the user clicks on the button, a pop-up should open and he should enter his contact number using gravity form and then the video will be shown to him.
Now I have a button on the page and an html element that displays the video through the iframe tag, and the default mode is display: none.

function custom_script() {
        ?>
        <script type="text/javascript">
      document.addEventListener('DOMContentLoaded', function () {
        // Event listener for form submission
        jQuery(document).on('gform_confirmation_loaded', function(event, formId){
            // Check if the submitted form is the one with ID 1
            if (formId == 1) {
                // Show the video element with ID 'wb-video'
                document.getElementById('wb-video').style.display = 'block';
            }
        });
    });
    
        </script>
        <?php
    }
    add_action('wp_footer', 'custom_script');

I put this code at the end of the functions.php file. But after the user completes the form, nothing happens on the page. The video is not displayed.
Thank you if you guide me.

Retrieving Variable Values with AJAX

I want to create a feature on a specific section of my custom template’s category page that allows users to sort the displayed cards in any order they prefer.

To achieve this, I’ve started by placing the following simple HTML code on the category.php page:

   <select id="bodyBTN_select_sort">
     <option id="Newest_mode_sort" value="selectNewest">Newest</option>
     <option id="Oldest_mode_sort" value="selectOldest">Oldest</option>
     <option id="MostViewed_mode_sort" value="selectMostViewed">Most Viewed</option>
     <option id="LeastViewed_mode_sort" value="selectLeastViewed">Least Viewed</option>
     <option id="Random_mode_sort" value="selectRandom">Random!</option>
   </select>

Now, I want the following paths to load on the page whenever a user selects one of the options:

<?php get_template_part('templates/archive-category-tag/sort-by_card/newest_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/oldest_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/most-viewed_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/least-viewed_theme'); ?>;

<?php get_template_part('templates/archive-category-tag/sort-by_card/random_theme'); ?>;

The only thing left to do is to use jQuery to get the user’s selected options and insert the corresponding path into the page.
Since my paths are in PHP and follow WordPress functions, I can’t directly insert them into the page using JavaScript. Therefore, I need to send the selected items to the server and a specific file for processing using AJAX.

For this purpose, I wrote the following jQuery code in a separate file:

$(document).ready(function() {
  let value_result = "selectNewest"; // The default value

  // Function to send data to PHP file
  function sendDataToPHP(value) {
    console.log('Request sent : ' + value);
      $.ajax({
          url: '/site/wp-content/themes/theme-pro/templates/functions/template/category_functions.php',
          type: 'POST',
          data: { sort_by: value },
          success: function(response) {
            // Check the content of the answer
            console.log('Server response :', response);

            // Replace element content with response
            $('#card_path_category').html(response);

             // Check for errors
            // if ($('#HNSC_card_path_category').html() === '') {
            //     console.error('The content of the element was not updated.');
            // }
          }
      });
  }

  // Change event function
  $('#bodyBTN_select_sort').change(function() {
      value_result = $(this).val();
      sendDataToPHP(value_result);
      console.log('Selected value :' + value_result);
  });

  // Send initial data
  sendDataToPHP(value_result);

  // Set the default option
  $('#Newest_mode_sort').prop('selected', true);
});

Now, I need to create a file named category_functions.php in the specified path (this file is essentially the separated codes from the functions.php file); and then receive the value sent from AJAX and insert the appropriate path into the page based on the user’s selection.

For this purpose, I placed the following code inside the category_functions.php file:

  function get_template_part_by_sort() {

    // Get the value sent via AJAX
      $sort_by = isset($_POST['sort_by']) ? $_POST['sort_by'] : 'selectNewest';
    
     // Check and display the received value for debugging
      var_dump($sort_by);
    
    
         // Check the value and determine the address
         switch ($sort_by) {
          case 'selectNewest':
              get_template_part('templates/archive-category-tag/sort-by_card/newest_theme');
              break;
          case 'selectOldest':
              get_template_part('templates/archive-category-tag/sort-by_card/oldest_theme');
              break;
          case 'selectMostViewed':
              get_template_part('templates/archive-category-tag/sort-by_card/most-viewed_theme');
              break;
          case 'selectLeastViewed':
              get_template_part('templates/archive-category-tag/sort-by_card/least-viewed_theme');
              break;
          case 'selectRandom':
              get_template_part('templates/archive-category-tag/sort_by_card/random_theme');
              break;
          default:
              // If the value passed is invalid, the default path is inserted.
              get_template_part('templates/archive-category-tag/sort-by_card/newest_theme');
      }
    }

After completing all the above steps, it’s time to get the output.

In the output, I can successfully receive the default value and the path that should be received in case of missing or problematic input, and the cards are sorted accordingly.

However, when I select other options, I still receive the same default path!

To find the error, I first printed the output values of the script file in the browser console as follows:

When selecting the Random! option:

Selected value :selectRandom
Request sent : selectRandom
Server response : <empty string>

By displaying the above output, I realized that the PHP processing file is not sending anything!

To do this, I used var_dump($sort_by); to get an output from my PHP codes and it printed the following text on the page for me:

string(12) "selectNewest"

The above value is the default value and remains constant when changing the select box and does not react to the output at all!?

I don’t have much control over AJAX and this is the first time I’ve written such an AJAX code.

My main goal is just to put the specified paths on the page based on the user’s selection and I couldn’t think of any other solution except AJAX.

Please help me complete the code and get the correct response from the server if my solution to this problem is correct.
And if my solution is not good, please guide me on what I should do to achieve my goal.

Thank you in advance for any help.

Argument type match with rest parameter in type alias and its implementation

Newbie to TypeScript, and I’m confused about the folowing snippet:

type Fn = (...args: number[]) => void

const fn1: Fn = (x) => console.log(x);
const fn2: Fn = (x1, x2) => console.log(x1, x2);

fn1(2);
fn2(2, 4);

In my understanding, ...args is a rest parameter where indefinite number of arguments is allowed and you can access args as array, but its implementations fn1 and fn2 doesn’t implement with rest parameter or access it as array. fn1 only accept 1 argument, and fn2accept 2 arguments only.

Is this a specific feature of rest parameter in type keyword? If so, where can I find the specfication?

Please feel free to tell me if there’s anything unclear to you.

I expected the implementaion of Fn should be something like

const fn: Fn = (...x: number[]) => console.log(x);

having problems in very simple and basic typescript program

the code is look like this:

const num1: number[] = [12, 14, 18, 22, 24];
const findNum: number | undefined = num1.find(elem => elem === 12);
console.log(findNum);

and the error I’m facing is:

1.ts:2:42 - error TS2550: Property 'find' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.

2 const findNum: number | undefined = num1.find(elem => elem === 12);
                                           ~~~~

Found 1 error in 1.ts:2

the tsconfig:

{
  "compilerOptions": {
    "target": "es2016",
    "lib": ["es2015"],
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

I’m using typescript version 5.5.4 and I tried it in the online typescript playground there it’s working without error.

but in my mutcin, it’s not working I tried uninstall typescript and after install but it’s still not working.

bad habbit of using chatGpt? [closed]

Am I developing a bad habit of learning with ChatGpt?
Primarely I’m using ChatGpt for learning how something works, let’s say “what are the methods of defense that developer use from preventing the cyber attacks on his web site, and which dev role exactly should do that”…. “how does the web hosting work, what are CDN’s and in which cases there are better then some local hosting.” and so on.
I usually always tell him I don’t want to see code, just explanation of how something work and why is that better decision, lets say we are talking about the fetch and axios in js.

So I’m wondering do I developing a bad habit of making that so much simpler and quicker for me instead of just searching on the others forums and web articles on my own. The main problem with forums and web articles is there is soo much different opinions and sometimes its hard to me decide what is better, because I don’t have soo much experience at the moment.

How to Correctly Reset and Re-generate a Math Quiz in JavaScript?

I’m working on a simple math quiz application using JavaScript, where users have to solve randomly generated math problems. I’ve written a function to handle the quiz logic and user interactions, but I’m encountering a few issues with resetting and re-generating the quiz.

const randomQuiz = (function() {
const firstPara = document.querySelector(".firstNumber");
const operatorPara = document.querySelector(".operator");
const secondPara = document.querySelector(".secondNumber");
const buttonIt = document.querySelector(".answer");
const inputAnswer = document.querySelector(".textanswer");
const container = document.querySelector(".container");
const answerGet = document.querySelector(".asnwerGet");
const didit = document.querySelector(".didit");
let randomOperator = ["*", "+", "-", "/"];

const quastion = {
    firstNumber: Math.floor(Math.random() * 100),
    operator: randomOperator[Math.floor(Math.random() * randomOperator.length)],
    secondNumber: Math.floor(Math.random() * 100),
};

buttonIt.addEventListener("click", () => {
    firstPara.textContent = quastion.firstNumber;
    operatorPara.textContent = quastion.operator;
    secondPara.textContent = quastion.secondNumber;
    container.append(firstPara);
    container.append(operatorPara);
    container.append(secondPara);
});

answerGet.addEventListener("click", () => {
    const answer = calculation();
    if (inputAnswer.value == answer) {
        console.log(`You did it`);
        didit.textContent = `You did it! The answer is ${calculation()} !!!!!`;
        resetGame();
    } else {
        console.log(`Nice try`);
        console.log(`Answer is ${calculation()}`);
    }
});

function calculation() {
    if (quastion.operator === "-") {
        return quastion.firstNumber - quastion.secondNumber;
    } else if (quastion.operator === "*") {
        return quastion.firstNumber * quastion.secondNumber;
    } else if (quastion.operator === "+") {
        return quastion.firstNumber + quastion.secondNumber;
    } else if (quastion.operator === "/") {
        return +(quastion.firstNumber / quastion.secondNumber).toFixed(2);
    }
}
    
function resetGame() {
    firstPara.textContent = "";
    operatorPara.textContent = "";
    secondPara.textContent = "";    
    // Here should be a mechanism to generate a new question
}
})();

My goal is everytime i get correct answer quastion will reset automatically.
but i am always getting same quastion for some reason i think problem is at buttonIt function always appending same value but how will i converting them into random ones ?
I’m also using querySelector to select DOM elements and append them to the container, but I’d like to know if there’s a more efficient approach.
The calculation function correctly computes the result based on the operator, so I believe the core logic is functioning as expected.
Thank you!
I’ve cleared the text content of the display elements, but this does not automatically generate new question values.
I tried adding new random values directly inside the resetGame function but need advice on integrating this properly.
Any suggestions or improvements to address these issues would be greatly appreciated!

How to use a string in javascript function

I have a button

onclick="click(' . $item . ');"

then the javascript function is supposed to pass $item to another page. It works fine if $item is a number, but not if it’s a string, and sometimes it’s a mix of characters and numbers which I can’t control.

function click(c)
{
var u = "items.php?serial=" + c;
document.location.href = u;
}

Is there a way to do this in JS?

After Register Confirmation Popup Script with RegisterStartupScript, Multiple Times Method Calling

The below picture shows the page developed in C#, This page contains some form elements text box, data table and buttons.

Error Case:
The user goes the another page (mostly time this is a classing list page) and redirect again to this form page. After that, user filling the form again and click any button.

In this scenario, GetStateFromUI trigger multiple times(with old form values and current filled form values therefore API trigger two times )

-> In addition to that, If user send forms one time(everything works), and again a second(current form and old form send to getstatefromui) and again third times multiple api calling(old forms and current form sending to the same getstatefromui method.).

Note: The users authenticate to application and filling form elements,after that click the any buttons. In this case everything works fine. API trigger one times.

I debugged it but I couldn’t catch error case when I try everytime api trigger one times. Everything works fine. Why this error happens? Somehow, users register more than one script and when one is triggered, the others are triggered as well but I can not prove it because I can not catch this error.

I am suspicious, this error’s reason is script registration. but I can not sure. I am thinking changing popup structure with no using script registration.

enter image description here

In Demo.aspx:

// Panel & TextBox & Datatable definitions and then buttons ...
<asp:button id="btn1" runat="server" Text="btn1" OnClick="btn1_Click" />
<asp:button id="btn2" runat="server" Text="btn1" OnClick="btn2_Click" />
<asp:button id="btn3" runat="server" Text="btn1" OnClick="btn3_Click" />
<asp:HiddenField ID="hdnButton1ConfirmCheck" />
<asp:HiddenField ID="hdnButton2ConfirmCheck" />
<asp:HiddenField ID="hdnButton3ConfirmCheck" />

<script type="text/javascript"> 
    ...
    if(data == 'Button1StartPopup') {
      $hdnButton1ConfirmCheck.setValue('Button1Confirm');
      __doPostBack('Button1StartPopup', '');
    }
    if(data == 'Button2StartPopup') {
      $hdnButton2ConfirmCheck.setValue('Button2Confirm');
      __doPostBack('Button2StartPopup', '');
    }
    if(data == 'Button3StartPopup') {
      $hdnButton3ConfirmCheck.setValue('Button3Confirm');
      __doPostBack('Button3StartPopup', '');
    }
    ...
</script>

In Demo.aspx.cs

public override void GetStateFromUI() {

string eventTarget = Request.Form["__EVENTTARGET"];
 if(eventTarget == "Button1StartPopup") {
      MyButton1Method();
 }

 if(eventTarget == "Button2StartPopup") {
      MyButton2Method();
 }

 if(eventTarget == "Button3StartPopup") {
       MyButton3Method();
 } 
}

privte void Button1Method(){
   if(!string.Equals(hdnButton1ConfirmCheck.Value, "Button1Confirm")) return;
   hdnButton1ConfirmCheck.Value = string.Empty;

   var request = new DemoRequestForButton1();
   var response = DemoServer.demoApi(request);
   if(response?.header != null && response?.header.Success) {
     ClientScript.RegisterStartupScript(Page.GetType(),"SuccessScript", "alert("Operation 
     Success");", true);
   } else {
      ClientScript.RegisterStartupScript(Page.GetType(),"FailedScript", "alert("Operation 
    Failed");", true);
    }
 }

 private void Button2Method(){
    if(!string.Equals(hdnButton2ConfirmCheck.Value, "Button2Confirm")) return;
    hdnButton2ConfirmCheck.Value = string.Empty;

    var request = new DemoRequestForButton2();
    var response = DemoServer.demoApi(request);
    if(response?.header != null && response?.header.Success) {
    ClientScript.RegisterStartupScript(Page.GetType(),"SuccessScript", "alert("Operation 
     Success");", true);
  } else {
   ClientScript.RegisterStartupScript(Page.GetType(),"FailedScript", "alert("Operation 
   Failed");", true);
  }
 }

  private void Button3Method(){
      if(!string.Equals(hdnButton3ConfirmCheck.Value, "Button3Confirm")) return;
      hdnButton3ConfirmCheck.Value = string.Empty;

       var request = new DemoRequestForButton3();
       var response = DemoServer.demoApi(request);
       if(response?.header != null && response?.header.Success) {
       ClientScript.RegisterStartupScript(Page.GetType(),"SuccessScript", "alert("Operation 
       Success");", true);
   } else {
     ClientScript.RegisterStartupScript(Page.GetType(),"FailedScript", "alert("Operation 
     Failed");", true);
   }
  }

    protected void Btn1_Click(object sender, EventArgs e) {
        RegisterScriptForButtons("Is Buttons1 Operation Work Ok", "Button1StartPopup");
    }

    protected void Btn2_Click(object sender, EventArgs e) {
        RegisterScriptForButtons("Is Buttons2 Operation Work Ok", "Button2StartPopup");
    }


    protected void Btn3_Click(object sender, EventArgs e) {
        RegisterScriptForButtons("Is Buttons3 Operation Work Ok", "Button3StartPopup");
    }


    protected void RegisterScriptForButtons(string popupMessage, string data) {
       string script = string.Format("$(document).ready(function(){ -- small confirmation popup code in different framework   });", "Operation Result", popupMessage );
       ClientScript.RegisterStartupScript(Page.GetType(),"ButtonOperation",script, true);
    }