Why audio request stays in pending state?

can anyone please help me with the problem i’m facing…
I want to generate audio from text using .NET framework.
I have written controller method as below:

public ActionResult ConvertToSpeech(string text)
        {
            // Convert text to speech using System.Speech.Synthesis
            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
            {
                MemoryStream memoryStream = new MemoryStream();
                synthesizer.SetOutputToWaveStream(memoryStream);
                synthesizer.Speak(text);
 
                // Reset memory stream position
                memoryStream.Position = 0;
 
                // Return audio file
                return new FileStreamResult(memoryStream, "audio/wav");
            }
        }

In html I have added audio tag:
<audio ng-src=”{{audioSource}}” type=”audio/wav” id=”captchaAudio” ng-hide=”true”></audio>


In angular js:
generateAudio: function () {
$scope.audioSource = "/ConvertToSpeech?timestamp=" + new Date().getTime();
setTimeout(function () { $scope.$apply(); }, 10);
}

after calling the method my request is in still in pending state

here is the image.. (https://i.stack.imgur.com/zmtKK.png)

can someone please help me fix it. i tried different fixes but the request stays in pending state.

Growing memory consumption when refresh data with anychart gantt

I have a simple anychart code for refreshing gantt chart, which is run every 1 second:

function init_schedule(){
    anychart.onDocumentReady(function () {
        anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) {
            document.getElementById("container").innerHTML = "";
            var treeData = anychart.data.tree(data, "as-tree");

            var chart = anychart.ganttResource(); 
            ...other logic, etc
       });
    });
}


var intervalId = setInterval(function() {
    init_schedule();
}, 1000);

if I run var chart = anychart.ganttResource() method in loop, the browser doesnt free memory for page, VM memory consumption is growing continously to infinity and the page starts to freeze.
Is there any other method to refresh gantt data from server?

I commented out all other code to find the reason on growing memory consumption. Did I make it wrong?

200 response code on a duplicate email (should be 400 response code) PHP Apache server

Im encountering an issue in my PHP code. When I enter an email into my form, and the POST request is sent to MYSQL server, it’s giving me a 200 response even if I enter a duplicate email. In my network I am getting an error that looks like this:

Received POST data:Array
(
    [csrfToken] => <?php echo generateCSRFToken(); ?>
    [first-name] => Moses
    [last-name] => Avigdor
    [email] => [email protected]
    [password] => gfdjgdfj
)
Sorry, there was an error uploading your file.<br />
<b>Fatal error</b>:  Uncaught mysqli_sql_exception: Duplicate entry '[email protected]' for key 'profile.email' in /opt/homebrew/var/www/ipn.php:60
Stack trace:
#0 /opt/homebrew/var/www/ipn.php(60): mysqli_stmt-&gt;execute()
#1 {main}
  thrown in <b>/opt/homebrew/var/www/ipn.php</b> on line <b>60</b><br /> 

Inside my console log I’m getting an affirmative response status: 200.

What I’m trying to do is have a 400 error when a duplicate email is entered and a 200 response when there is no duplicate.

This is my PHP code.

    <?php
    error_reporting(E_ALL);


    header("Access-Control-Allow-Origin: *");

    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");

    header("Access-Control-Allow-Headers: Content-Type, Access-              Control-Allow-Headers, Authorization, X-Requested-With");

    header('Content-Type: application/json');


    session_start();


    $servername = "localhost";
    $username = "root";
$password = "Proverbs31!";
$database = "IPN";

// Assign values from the form data to variables
$first_name = $_POST['first-name'];
$last_name = $_POST['last-name'];
$email = $_POST['email'];
$user_password = $_POST['password']; 

// Check if email already exists
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check if email already exists
$sql = "SELECT COUNT(*) AS count FROM profile WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$count = (int) $row['count'];

if ($count > 0) {
   // Email address already exists, send a client error response
   http_response_code(409); // Conflict
   echo json_encode(array("error" => "Email address already exists"));
   exit(); // Stop further execution
}

// If email doesn't exist, proceed with insertion




// Handle profile picture upload
$profile_picture = null;
if(isset($_FILES['profile-picture'])) {
    $file_name = $_FILES['profile-picture']['name'];
    $file_tmp = $_FILES['profile-picture']['tmp_name'];
    $file_size = $_FILES['profile-picture']['size'];
    $file_type = $_FILES['profile-picture']['type'];

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($file_name);

    // Move uploaded file to target directory
    if (move_uploaded_file($file_tmp, $target_file)) {
        $profile_picture = $target_file;
    } else {
        // Handle file upload error
        http_response_code(500); // Internal Server Error
        echo json_encode(array("success" => false, "message" => "Error uploading profile picture"));
        exit();
    }
}

// Proceed with insertion
$sql = "INSERT INTO profile (first_name, last_name, email, password, profile_picture) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $first_name, $last_name, $email, $user_password, $profile_picture); 

try {
    // Attempt to execute the prepared statement
    if ($stmt->execute()) {
       
        http_response_code(200); // OK
        echo json_encode(array("success" => true, "message" => "Signup successful"));
    } else {
   
        http_response_code(500); 
        echo json_encode(array("error" => "An unexpected error occurred"));
    }
} catch (mysqli_sql_exception $e) {
  
    error_log("MySQLi SQL Exception: " . $e->getMessage());

    if ($e->getCode() == 1062) { 
     
        http_response_code(409); 
        echo json_encode(array("error" => "Email address already exists"));
    } else {
        
        http_response_code(500); 
        echo json_encode(array("error" => "An unexpected error occurred"));
    }
} catch (Exception $e) {
   
    error_log("Exception: " . $e->getMessage());
    
    
    http_response_code(500); 
    echo json_encode(array("error" => "An unexpected error occurred"));
} finally {
  
    $stmt->close();

    
    $conn->close();
}


And here is my JavaScript

// Define the handleSubmit function
function handleSubmit(event) {
  event.preventDefault(); // Prevent default form submission

  const form = event.target;
  const formData = new FormData(form);

  // Fetch API to send POST request to ipn.php with form data
  fetch('http://127.0.0.1:8080/ipn.php', {
    method: 'POST',
    body: formData, 
  })
    .then((response) => {
      console.log('Response status:', response.status);

      if (response.status === 200) {
       
        form.reset();

        // window.location.href = 'login.html';
      } else if (response.status === 409) {
        // Check if response is JSON
        return response
          .json()
          .then((data) => {
            console.log('Response:', data);
            // Display error message if email already exists
            const errorMessage = document.getElementById('error-message');
            errorMessage.textContent = data.message; // Set the error message content
            errorMessage.style.display = 'block'; // Show the error message
            console.log('Parsed JSON data:', data);
          })
          .catch((error) => {
            console.error('Error parsing JSON:', error);
            
            const errorMessage = document.getElementById('error-message');
            errorMessage.textContent =
              'An error occurred. Please try again later.';
            errorMessage.style.display = 'block'; 
          });
      }
    })
    .catch((error) => {
      console.error('Fetch error:', error); 
    });
}


document.getElementById('signup-form').addEventListener('submit', handleSubmit);

In MySQL I have a table with a column designated email and it is unique.

I tried to move the try statement around, specifically where the 200 code is tripped. This was primarily because the 200 code is being recieved before the MySQL workbench gives its 1062 code. I’ve tried to specify the error codes like this:

try {
    // Attempt to insert data into the database
    $sql = "INSERT INTO profile (first_name, last_name, email, password) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssss", $first_name, $last_name, $email, $password);
    $stmt->execute();

    // If insertion was successful, send a success response
    http_response_code(200); // OK
    echo json_encode(array("success" => true, "message" => "Signup successful"));
} catch (mysqli_sql_exception $e) {
    // Handle duplicate entry error
    if ($e->getCode() == 1062) { // MySQL error code for duplicate entry
        // Send an error response indicating duplicate entry
        http_response_code(409); 
        echo json_encode(array("error" => "Email address already exists"));
    } else {
        // Handle other MySQLi SQL exceptions
        http_response_code(500); // Internal Server Error
        echo json_encode(array("error" => "An unexpected error occurred"));
    }
}

This resulted in a json parsing error. I also tried to change up my JavaScript to handle the errors first then move on to a 200 code

if (response.status !== 200) {
    // Handle non-successful HTTP status codes (e.g., 409 for duplicate entry)
    return response.json()
      .then((data) => {
        
        const errorMessage = document.getElementById('error-message');
        errorMessage.textContent = data.error;
        errorMessage.style.display = 'block';
      })
      .catch((error) => {
        console.error('Error parsing JSON:', error);
        
        const errorMessage = document.getElementById('error-message');
        errorMessage.textContent = 'An error occurred. Please try again later.';
        errorMessage.style.display = 'block';
      });
  }

This had no affect on the outcome that I can tell. Needless to say I need help.

How to create a Qr Code in Sap Build apps

im currently working on a project im trying to generate a qr code with a given input data by the user from what i tried from what i tried so far is that apis dont work and i cannot use require from what i tried atleast if anyone has some experience with Sap build apps and knows how to use an api like qrcode.js etc or has a clue for a solution id be glad to hear it

Well as already explained i tried calling an api i also tried using require but none of my tried attempts has led to any actual useful result nor show worthy

Cypress – setData() not available to type RchText editor in Iframe

I have a RichText editor as shown in below screenshot

enter image description here

so to type in that rich text editor I’m using below code

const ele = await promisify(cy.get('iframe[title="Rich Text Editor, question"]'));
const body = ele.contents().find("body")[0];
await promisify(cy.wrap(body ).type("My looooong text"))

but above code is very SLOW. It types character by character.

I want to use setData() with coding like below (which is very fast)

enter image description here

I tried everything. Below is one example I tried

const question = await promisify(cy.get('#frmQuestion iframe[title="Rich Text Editor, question"]'));
          question.contents().find("body")[0].then((el => {
              // @ts-ignore
              const editor = el[0].ckeditorInstance  // If you're using TS, this is ReturnType<typeof InlineEditor['create']>
              editor.setData('Typing some stuff')
          }));

I realized ckeditorInstance NOT available with anything I tried so I’m getting error similar to “cannot execute setData() for undefined”

So how to use setData in my situation where user have iframe ?

How to make a table of 2 columns from a list?

I have a list var words=['ac', 'bd', 'bf','uy','ca'];

I want to form a table of 2 columns listing all these words one after another from left to right.

The result table should be

<table id="wordTable">
 <tr>
   <td>ac </td>   <td>bd </td>
 </tr>
 <tr>
   <td>bf </td>   <td>uy </td>
 </tr>
 <tr>
   <td>ca </td>   <td> </td>
 </tr>

</table> 

This javascript code does not work

function showWords(){
  row_Index=0;
  for (const myWord of words)
  {
    if (row_Index==0){
     document.getElementById("wordTable").innerHTML +="<tr>";      
     document.getElementById("wordTable").innerHTML += "<td>"+ myWord +"</td>";
     }
     else if (row_Index==1){
     document.getElementById("wordTable").innerHTML += "<td>"+ myWord +"</td>";

     document.getElementById("wordTable").innerHTML +="</tr>";        
     }
     else if (row_Index==2){
        row_Index=0;
     }
     row_Index++;
  }
}

How to create that table from the list?

Also, how to clear all the rows and columns of the table?

document.getElementById("wordTable").clear();

or document.getElementById("wordTable").remove();

don’t work

How to make a marquee that only moves on hover? (Paused marquee until onmouseover)

I am trying to make a marquee that only scrolls when the mouse is pointing and resets back and pauses (paused state) after onmouseout.
I have tried the codes below, I found this codes in another stackoverflow question.
But my question is how do I make marquee pause or stop permanently and only move on hover?
I have tried adding marquee attributes in css but it does not work in css.I have a few and bit of knowledge in javascript but maybe in javascript it will work?
I just don’t know how to make the marquee permanently paused and only move on hover, then reset and pause like a “slide” behavior marquee after mouseout.

<marquee onmouseover="start()" onmouseout="stop()">This is the normal Marquee</marquee>
<marquee behavior="alternate" onmouseover="start()" onmouseout="stop()">This is the alternate Marquee</marquee>
<marquee behavior="slide" onmouseover="start()" onmouseout="stop()">This is the slide Marquee</marquee>

How to replace \ to ?

occur error: Uncaught SyntaxError: Invalid or unexpected token

console.log(
  "\left\{ \frac{\partial \mu _j}{\partial t}\right\} _{\alpha =1} =\frac{\hbar }\kappa\, \frac{\partial c^*_j(\mu ,T)}{\partial \mu _j}\cdot \left(\begin{array}{cc} \sqrt{\frac{\kappa}{M}}\, \frac{1}{j}\, \langle \Phi \rangle \,\sqrt{\mu _j-\mu } & \sqrt{\frac{\kappa}{M}}\, j\, \langle \Phi \rangle \,\sqrt{\mu _j-\mu } \\ \frac{1}{j}\, \sqrt{\frac{\kappa}{M}}\, \frac{1}{j} \, \langle \Phi \rangle \,\sqrt{\mu _j-\mu } &\frac{1}{j}\,\sqrt{\frac{\kappa}{M}}\, \frac{1}{j}\, \langle \Phi \rangle \,\sqrt{\mu _j-\mu }\end{array}\right) \, \, .n公式(0,481),(1000,969),nLatex格式输出:\sum_{\alpha} \frac{\partial h_{\alpha}(\Phi)}{\partial t}\frac{\partial T}{\partial t}=\frac{\partial c_{\alpha}(\mu,T)}{\partial T}\left. h_{\alpha}(\Phi)\right|_{\mu},\qquad \left.\frac{\partial T}{\partial \mu}\right|_{\mu}="
    .replace(/\/g, '')
);

how to print data from sql database and print according to conditions and loops

i want to print loop according to the number of blocks, like if block is 1, then they print where catCnt = 1 only once and then they print one more content, which is included in wdgt-lft section where catCnt = 2 then after they print 4 post in wdgt-rgt section where catCnt = 2 .

Explanation : i have table which name is posts and second table is name is category i want to i and i have block of html code which is mention below i want to print all main block contained repeatedly according to Block value which is store in category table then i want to print big container value where catCnt which is in the posts table is = 1 so they print that in value in big container which is in the left block and then i want to print small container value which is also in the posts table where caatCnt = 2 and after i want to print 4 times right block value where catCnt = 2 but its is not equal to previous one small container which is in the left block and according to block if block is 2 then the whole prosier work same but there data is to be different from previous one in short all value is printed that is different

code which i tried to use :-

<?php 
$count = 1;
while ($count <= $row['Block']) {
    $query1cnt = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM posts WHERE Is_Active = 1 AND CategoryId= '$cattid' And catCnt= 1"));
    $query2cnt = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM posts WHERE Is_Active = 1 AND CategoryId= '$cattid' And catCnt= 2"));

?>
<!-- ============= MAIN BLOCK Start ================ -->
<div class="wdgt-wrap">
    <!-- =========left block start ========== -->
    <div class="wdgt-lft">
        <!-- Big Container Start here -->
        <a class="card-lg" data-nid="9418808"
            href="http://localhost/jhbnews/newsdetail.php?postid=<?php echo htmlentities($query1cnt['id'])?>"
            title="<?php echo htmlentities($query1cnt['PostTitle'])?>">
            <i class="img-sizer"></i>
            <img class="lozad lazy-img card-img" width="466px" height="262px"
                src="../admin/postimages/<?php echo htmlentities($query1cnt['PostImage']);?>"
                data-src="AddDatasrc" title=" <?php echo htmlentities($query1cnt['PostTitle'])?>"
                alt=" <?php echo htmlentities($query1cnt['PostTitle'])?>" />
            <h2 class="big-news-title">
                <?php echo htmlentities($query1cnt['PostTitle'])?>
            </h2>
        </a>
        <!-- Big Container Start here -->
        <!-- left Small Container Start here -->
        <a href="http://localhost/jhbnews/newsdetail.php?postid=<?php echo htmlentities($query2cnt['id']);?>"
            data-nid="9418878" class="card-sm card-sm-devider lft-card-m"
            title="<?php echo htmlentities($query2cnt['PostTitle'])?>">
            <div class="sm-lft">
                <i class="img-sizer"></i>
                <img class="lozad card-img lazy-img"
                    src="../admin/postimages/<?php echo htmlentities($query2cnt['PostImage']);?>" width="125px"
                    height="70px" data-src="datasrc" alt="<?php echo htmlentities($query2cnt['PostTitle'])?>"
                    title="<?php echo htmlentities($query2cnt['PostTitle'])?>" />
            </div>
            <div class="sm-rght">
                <h3 class="wdgt-subtitle1">
                    <?php echo htmlentities($query2cnt['PostTitle'])?>
                </h3>
                <span class="tm-stmp"><?php echo htmlentities($query2cnt['PostingDate'])?></span>
            </div>
        </a>
        <!-- left Small Container End here -->
    </div>
    <!-- =========left block End ========== -->
    <!-- =========Right  block Start ========== -->
    <div class="wdgt-rgt">
        <?php 
         $querynxt=mysqli_query($con,"SELECT * FROM posts WHERE Is_Active = 1 AND CategoryId= '$cattid' And homeCnt= 2 limit 6;");
         while ($roww=mysqli_fetch_array($querynxt)) {
            if ($roww["id"] != $query2cnt["id"]){
        ?>
             <a href="http://localhost/jhbnews/newsdetail.php?postid=<?php echo htmlentities($roww['id'])?>"
            data-nid="9418409" class="card-sm card-sm-devider" title="<?php echo htmlentities($roww['PostTitle'])?>">
            <div class="sm-lft">
                <i class="img-sizer"></i>
                <img class="lozad card-img lazy-img"
                    src="http://localhost/jhbnews/admin/postimages/<?php echo htmlentities($roww['PostImage'])?>"
                    width="125px" height="70px" data-src="Datasrc" title="<?php echo htmlentities($roww['PostTitle'])?>"
                    alt="<?php echo htmlentities($roww['PostTitle'])?>" />
            </div>
            <div class="sm-rght">
                <h3 class="wdgt-subtitle1">
                    <?php echo htmlentities($roww['PostTitle'])?>
                </h3>
                <span class="tm-stmp"><?php echo htmlentities($roww['PostingDate'])?></span>
            </div>
        </a>
        <?php }}?>
    </div>
      <!-- =========Right  block Start ========== -->
</div>
<!-- ============= MAIN BLOCK Start ================ -->

<?php $count++;
}?>

i tried many method but not get proper result please help me to find it

How to make bubble and Time in react-native-gifted-chat side by side

enter image description here

When I implemented it, bubble and Time were split into left and right ends.

Actual source code

<View style={styles.incomingContainer}> <Bubble {...props} containerStyle={{right:{ justifyContent:'flex-end',borderColor:'red',borderWidth:1,}}} renderTime={() => null} /> {renderTime(props)} </View>

I want to put Bubble and time next to each other without opening the margin as shown in the image.

enter image description here

How can I stop automatic submit after finishing all Input in a Form? (react-hook-form)

So I created a multi-step-form using shadcn, next, zod and react-hook-form. I have a problem wherein the form submitted on step 3 which is not what I want.

form.tsx

    const form = useForm<Inputs>({
        resolver: zodResolver(formSchemaData),
        defaultValues: {
          title: "",
          email: "",
          fullName: "",
          department: "",
          dateOfEvent: "",
          purpose: "",
          staringTime: "",
          endingTime: "",
          doesHaveDryRun: "",
          dryRunDate: "",
          dryRunStart: "",
          dryRunEnd: "",
        },
      });
    
      function onSubmit(values: any) {
        console.log(values);
      }
    
      const goToNextPage = async () => {
        const fields = steps[currentFormPage].fields;
        const output = await form.trigger(fields as FieldName[], {
          shouldFocus: true,
        });
    
        if (!output) return;
    
        if (currentFormPage < steps.length - 1) {
          setPreviousStep(currentFormPage);
          setCurrentFormPage((step) => step + 1);
        }
    
      };

So for example here. I didn’t hit the next button yet so nothing is showing in my console.

enter image description here

But when I press the next button, the form console.log the data even though it should be on submit button.

enter image description here

This is the full code.

Stripe “/create-payment-intent” 404

I am making a simple stripe recurring payment processor and I keep getting a POST error with a 404 for my create-payment-intent. These are also the errors i am getting in my console when I try to look at it. I am able to see the post working through Insomnia, but connecting it to my frontend is not working.

POST http://localhost:5173/create-payment-intent 404 (Not Found)
(anonymous) @ App.jsx:18
commitHookEffectListMount @ react-dom_client.js?v=1b04ad3d:16904
invokePassiveEffectMountInDEV @ react-dom_client.js?v=1b04ad3d:18320
invokeEffectsInDev @ react-dom_client.js?v=1b04ad3d:19697
commitDoubleInvokeEffectsInDEV @ react-dom_client.js?v=1b04ad3d:19682
flushPassiveEffectsImpl @ react-dom_client.js?v=1b04ad3d:19499
flushPassiveEffects @ react-dom_client.js?v=1b04ad3d:19443
(anonymous) @ react-dom_client.js?v=1b04ad3d:19324
workLoop @ react-dom_client.js?v=1b04ad3d:197
flushWork @ react-dom_client.js?v=1b04ad3d:176
performWorkUntilDeadline @ react-dom_client.js?v=1b04ad3d:384
Show 10 more frames
Show less
VM149:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
    at App.jsx:23:26
App.jsx: 
import React, { useState, useEffect } from "react";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";

import CheckoutForm from "./CheckoutForm";
import "./App.css";

// Make sure to call loadStripe outside of a component’s render to avoid
// recreating the Stripe object on every render.
// This is your test publishable API key.
const stripePromise = loadStripe("pk_test_51P0HqXLUshuizymb87sieUj8dR6IrsTqqQGINvIrdWpLDPgTMOEM1OkvnDpPGyxa4lUv7tXDlShU5SJjdV3RduZg00Y6RRHSi8");

export default function App() {
  const [clientSecret, setClientSecret] = useState("");

  useEffect(() => {
    // Create PaymentIntent as soon as the page loads
    fetch("/create-payment-intent", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ items: [{ id: "xl-tshirt" }] }),
    })
      .then((res) => res.json())
      .then((data) => setClientSecret(data.clientSecret));
  }, []);

  const appearance = {
    theme: 'stripe',
  };
  const options = {
    clientSecret,
    appearance,
  };

  return (
    <div className="App">
      {clientSecret && (
        <Elements options={options} stripe={stripePromise}>
          <CheckoutForm />
        </Elements>
      )}
    </div>
  );
}

Here is my checkout form.

CheckoutForm.jsx:
import React, { useEffect, useState } from "react";
import {
  PaymentElement,
  useStripe,
  useElements
} from "@stripe/react-stripe-js";

export default function CheckoutForm() {
  const stripe = useStripe();
  const elements = useElements();

  const [message, setMessage] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!stripe) {
      return;
    }

    const clientSecret = new URLSearchParams(window.location.search).get(
      "payment_intent_client_secret"
    );

    if (!clientSecret) {
      return;
    }

    stripe.retrievePaymentIntent(clientSecret).then(({ paymentIntent }) => {
      switch (paymentIntent.status) {
        case "succeeded":
          setMessage("Payment succeeded!");
          break;
        case "processing":
          setMessage("Your payment is processing.");
          break;
        case "requires_payment_method":
          setMessage("Your payment was not successful, please try again.");
          break;
        default:
          setMessage("Something went wrong.");
          break;
      }
    });
  }, [stripe]);

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!stripe || !elements) {
      // Stripe.js hasn't yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return;
    }

    setIsLoading(true);

    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        // Make sure to change this to your payment completion page
        return_url: "http://localhost:3000",
      },
    });

    // This point will only be reached if there is an immediate error when
    // confirming the payment. Otherwise, your customer will be redirected to
    // your `return_url`. For some payment methods like iDEAL, your customer will
    // be redirected to an intermediate site first to authorize the payment, then
    // redirected to the `return_url`.
    if (error.type === "card_error" || error.type === "validation_error") {
      setMessage(error.message);
    } else {
      setMessage("An unexpected error occurred.");
    }

    setIsLoading(false);
  };

  const paymentElementOptions = {
    layout: "tabs"
  }

  return (
    <form id="payment-form" onSubmit={handleSubmit}>

      <PaymentElement id="payment-element" options={paymentElementOptions} />
      <button disabled={isLoading || !stripe || !elements} id="submit">
        <span id="button-text">
          {isLoading ? <div className="spinner" id="spinner"></div> : "Pay now"}
        </span>
      </button>
      {/* Show any error or success messages */}
      {message && <div id="payment-message">{message}</div>}
    </form>
  );
}

Here is my server.js file

const express = require("express");
const app = express();
require("dotenv").config();
const stripe = require("stripe")(process.env.SECRET_KEY);

app.use(express.static("public"));
app.use(express.json());

const calculateOrderAmount = (items) => {
  // Your calculation logic here
  return 1400; // Example amount, replace with actual calculation
};

app.post("/create-payment-intent", async (req, res) => {
  const { items } = req.body;

  try {
    // Create a PaymentIntent with the order amount and currency
    const paymentIntent = await stripe.paymentIntents.create({
      amount: calculateOrderAmount(items),
      currency: "usd",
      // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default.
      automatic_payment_methods: {
        enabled: true,
      },
    });

    res.json({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (error) {
    console.error("Error creating payment intent:", error);
    res.status(500).json({ error: "Failed to create payment intent" });
  }
});

app.listen(5000, () => {
  console.log("Server is running on http://localhost:5000");
});

Thanks for the help!

how to implement single delete task function in To-do app? [closed]

Been trying to debug and try to find the solution but am very confused

The git hub link is https://github.com/kevtheman98/To-do
and the function is in the storage file

I want the function to go through the local storage, if the item is in local storage and it matches the id of the parent of the delete button, then it removes it. And then for every item after that it changes the index by subtracting one so it is still in order

I am doing this from the Odin project so any tips on how to make the code better or other approaches are appreciated

Same question different example, why use bind ()? [duplicate]

I must say your answers on my recent question have been very helpful, but I don’t think I asked the right question. I understand what happens when this does not have context, it defaults to the window object. I also understand that this is a substitute for the obj it is referring to. I did some more tinkering and found something interesting, when I called obj.func(this.addToList) (when I took out the bind as a test) as obj.func(obj2.addToList) the same error popped up, meaning the this.addToList isn’t the issue I think? Moving on, instead of the way my book did it, I wrote my own code where I call a method off of an a different object and pass in a function from the original object as a parameter, like so.

const obj = {
    list: [], 
    func(callback) {
       callback(5);
    }
};
const obj2 = {
    list: [], 
    addToList(value) {
        this.list.push(value);
    }, 
    method() {
        obj.func(this.addToList.bind(this));
    }
};

Nothing too complicated, pretty cut dry, but essentially the same elements as my last question. So I added list on both objects to see if when I called obj.func(this.addToList.bind(this)); with and without bind, to see if this would refer to the first object instead of the second, like I suspected it might, neither were the case. Then I tried to call obj.func(this.addToList.bind(this)) without the bind and no such luck. The response was that the console could not read an undefined reading of push or something of those lines. I just truly do not understand why this.addToList does not refer to obj2 because it is a method of the object itself, and called in it as well. The only theory I have is that the argument is doing something to it obviously I just don’t know what. I believe everything has an explanation of some kind, somehow so even if the computer has some weird way of doing things there still has to be some reason right? I want to know and understand that reason. My question in summary is ‘Why is the context changed when the method is used as an argument?’ because I understand that is why the bind () method is needed.

Facebook In-App browser doesn’t not allow for download image file

I have a project create and download image on frame with our site by javascript. After user move, zoom upload image on frame then create image and download to drive storage. With any browser in PC so it’s working but when i click link from facebook or facebook messenger so facebook in-app browser does’nt allow download image when click download button, it say “Can’t load page”. But when i open link by external brower all function working. Can you help me some solutions pls
This is create image function and way i do:

// Create and Download
        function createImage() {
            const mergedCanvas = document.createElement('canvas');
            const mergedContext = mergedCanvas.getContext('2d');
            
            //Draw image on frame //

            const mergedImageUrl = mergedCanvas.toDataURL('image/png');
            const link = document.createElement('a');
            link.href = mergedImageUrl;
            link.download = 'merged_image.png';
            link.target = '_blank'; // Mở liên kết trong một tab hoặc cửa sổ mới
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
//HTML
<button class="download-image">Download</button>

I tried detecting the link open with facebook in-app browser and then forcing it to open with an external browser, but all methods failed to force facebook to open with an external browser to download.