How do i fix .src property not working in javascript?

So I am writing code that changes an image depending on random number.

here is my code:

let r = Math.floor(Math.random()*8+1)

let p = document.getElementsByClassName("imgs");

switch (r) {
    case 1:
        p[0].src = 'img1.jpg';
        break;
    case 2:
        p[1].src = 'img2.jpg';
        break;
    case 3:
        p[2].src = 'img3.jpg';
        break;
    case 4:
        p[3].src = 'img4.jpg';
        break;
    case 5:
        p[4].src = 'img5.jpg';
        break;
    case 6:
        p[5].src = 'img6.jpg';
        break;
    case 7:
        p[6].src = 'img7.jpg';
        break;
    case 8:
        p[7].src = 'img8.jpg';
        break;
    default:
        break;
    }

but it doesn’t work, the image is still the same.

I know that this question was asked a few times but i tried many solutiotions with no effect
the answer may be obvious, but I am beginner programmer and this is my first bigger project in js.

Make a payment with Stripe

I’ve been following this documentation of setting a Stripe payment element to collect card information: https://stripe.com/docs/payments/payment-element/migration?locale=en-GB

In my page I have created the container in which the payment element will mount into:

<form id="payment-form" onsubmit="event.preventDefault();">
    <div id="payment-element"></div>

    <div id="submit-container" class="d-none row mt-3 px-2">
        <button id="submit-btn" type="submit" class="submit disabled">Submit</button>
    </div>

    <div id="error-message"></div>
</form>

In my JavaScript I have the following:

var stripe;
var paymentElement;

$(document).ready(function () {
    showSpinner();
    initializeStripe();
    const form = document.getElementById('payment-form');
    form.addEventListener('submit', async (event) => confirm('@Model.ApplicationId'));
});

async function confirm(id) {
    showSpinner('Processing');
    debugger;
    const { clientSecret: clientSecret } = await makeAjaxCall('/payment/create-intent/' + id);
    const { error } = await stripe.confirmPayment({
        paymentElement,
        clientSecret,
        redirect: "if_required"
    });

    if (error) {
        console.log(error);
    }
}

function initializeStripe() {
    stripe = Stripe('@stripeOptions.Value.PublishableKey');

    const elements = stripe.elements({
        mode: 'payment',
        currency: 'gbp',
        amount: @Model.Amount
    });

    paymentElement = elements.create('payment');
    paymentElement.mount('#payment-element');

    paymentElement.on('ready', function (event) {
        hideSpinner();
        var cardImages = document.getElementById('card-images');
        var submitContainer = document.getElementById('submit-container');
        cardImages.classList.remove("d-none");
        submitContainer.classList.remove("d-none");
    });

    paymentElement.on('change', function (event) {
        var button = document.getElementById('submit-btn');
        if (event.complete) {
            button.classList.remove("disabled");
        } else {
            button.classList.add("disabled");
        }
    });
}

As you can see, when the form is submitted, I call an endpoint which I’ve created to create the intent and then use the ClientSecret to confirm the stripe payment. B

Below is essentially what the create-intent endpoint does:

StripeConfiguration.ApiKey = stripeOptions.Value.Secret;
var _paymentIntentService = new PaymentIntentService();
var intentOptions = new PaymentIntentCreateOptions
{
    Amount = parameters.Amount * 100, // 2000
    Currency = "gbp",
    PaymentMethodTypes = new List<string> { @"card" }
};

try
{
    var intent = await _paymentIntentService.CreateAsync(intentOptions);
    return intent.ClientSecret;
}
catch (Exception ex)
{
    return null;
}

However, when stripe.confirmPayment() is called, despite providing the correct parameters according to the documentation, the payment fails and I get an error with the following code:

payment_intent_unexpected_state

Does anyone know what I may be doing wrong here? It’s driving me insane!

Update:
Just had a look at the Stripe dashboard and noticed this error:

You cannot confirm this PaymentIntent because it's missing a payment method. You can either update the PaymentIntent with a payment method and then confirm it again, or confirm it again directly with a payment method.

The documentation doesn’t mention anything about creating a payment method so I’m rather confused now

Uncaught ERROR Invalid hook call. Hooks can only be called inside of the body of a function component

I was developing a profile of my portfolio using reactJS.
While I was using typical in my profile page,

code:

import "./Profile.css";
import Typical from "react-typical";

export default function Profile() {
  return (
    <div className="profile-container">
      <div className="profile-parent">
        <div className="profile-details">
          <div className="colz">
            <div className="colz-icon">
              <a #">
                <i className="fa fa-facebook-square" />
              </a>
              <a href="#">
                <i className="fa fa-linkedin-square" />
              </a>
              <a href="#">
                <i className="fa fa-instagram" />
              </a>
              <a href="#">
                <i className="fa fa-github-square" />
              </a>
            </div>
            <div className="profile-details-name">
              <span className="primary-text">
                Hello, I'M <span className="highlighted-text">ANUP</span>
              </span>
            </div>

            <div className="profile-details-role">
              <span className="primary-text">
                <h1>
                  <Typical //Error comes after i try to import this here
                  
                  />
                </h1>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

There was no error in ide-terminal, but it shows the following error in the browser:
Uncaught runtime errors: × ERROR Invalid hook call. Hooks can only be called inside of the body of a function component.

What can be the reason?
I appreciate any help you can provide.

Static files and scripts not found when using dynamic endpoints in Express.js application

I’m encountering an issue with my Express.js application where static files and scripts are not being found when accessing a specific endpoints. Here’s a breakdown of the problem:

I have an Express.js application with various routes serving HTML pages along with static files such as CSS, JavaScript, and images. Most endpoints work fine and serve the expected content, including the static files and scripts.

However, when I access the dynamic endpoints, say /team/:memberName, the static files and scripts cannot be found, leading to errors like:

Sandra%20Olson:19 Refused to apply style from 'http://localhost:4000/Sandra%20Olson:19
testimonial/assets/css/color-schemes/default.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Here are all of the errors:

enter image description here

Here is my App.js:

const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const util = require("util");

const homeJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "home.json"))
);
const menuJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "menu.json"))
);
const servicesJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "services.json"))
);
const blogsJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "blogs.json"))
);
const testimonialsJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "testimonials.json"))
);
const footerJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "footer.json"))
);
const cosmeticsJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "services", "cosmetics.json"))
);
const asideJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "services", "aside.json"))
);
const storeJSON = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "store.json"))
);
const contactJSON = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "contact.json"))
);
const galleriesJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "galleries.json"))
);
const teamJSON = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "team.json"))
);

const faqsJson = JSON.parse(
  fs.readFileSync(path.resolve("json", "en", "faq.json"))
);

const renderAsync = util.promisify(app.render).bind(app);
console.log(menuJson);

app.use(express.static(path.resolve("./public")));
app.set("view engine", "ejs");

app.get("/", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "home",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("index", {
    serviceDetails: servicesJson,
    blogDetails: blogsJson,
    testimonialDetails: testimonialsJson,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
    ...homeJson,
  });
});

app.get("/services", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "services",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("services", {
    serviceDetails: servicesJson,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/services/:name", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "services",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("service", {
    serviceDetails: cosmeticsJson,
    aside: asideJson,
    selection: req.params.name,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/store", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "store",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("store", {
    details: storeJSON,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/blog", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "about us",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("blogs", {
    blogs: blogsJson,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/galleries", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "about us",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("gallery", {
    galleries: galleriesJson,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/team", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "about us",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("team", {
    team: teamJSON,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/contact", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "contact",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("contact", {
    details: contactJSON,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.get("/testimonials", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "contact",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("testimonials", {
    details: testimonialsJson,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

app.post("/message", async (req, res) => {
  console.log("Success");
  res.sendStatus(200);
});

module.exports = app;

app.get("/faq", async (req, res) => {
  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "faq",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });
  res.status(200).render("faq", {
    faqs: faqsJson,
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});



app.get("/testimonial/:authorName", async (req, res) => {
  const authorName = req.params.authorName;
  const testimonial = testimonialsJson.find(testimonial => testimonial.author.name === authorName);
  
  if (!testimonial) {
    return res.status(404).send('Testimonial not found');
  }

  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "contact",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });

  res.status(200).render("detailed_testimonial", {
    details: [testimonial], // Wrapping in an array because your EJS template is expecting an array
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});




app.get("/team/:memberName", async (req, res) => {
  const memberName = req.params.memberName;
  const member = teamJSON.find(member => member.name === memberName);

  if (!member) {
    return res.status(404).send('Team member not found');
  }

  const headerHtml = await renderAsync("components/header", {
    menu: menuJson,
    selection: "contact",
  });
  const footerHtml = await renderAsync("components/footer", {
    info: footerJson,
  });

  res.status(200).render("person_page", {
    member: member, // Change here to match EJS template variable
    html: {
      header: headerHtml,
      footer: footerHtml,
    },
  });
});

So, if I try to access http://localhost:4000/testimonials the CSS and JavaScript is working, but if I try to access any of the dynamically created endpoints, for example the detailed page of any testimonial – http://localhost:4000/testimonial/Sandra%20Olson, the CSS and JavaScript can not be found.

Actually, I know from where is the problem and I hope you also understood from where is the problem, but I can not understand how to fix it!

Shopify: limit quantities of products ordered using code (no apps)

I’m trying to limit the quantity of a certain product per order. I want the customer to be able to buy no more than 2 of this product at once (plus other items if they want).

I already found this code:
https://github.com/carolineschnapp/limiter
I use Minimog 4.0 theme and I tried to configure it but it seems a bit old and does not work any more.

If anyone can tell me what’s wrong with this code, or provide another way to limit products quantities.

twitter timeline – show aonly the last 20 tweets

twitter-timeline

I have this piece of code in my HTML pagr

<div class="container" >
    <a class="twitter-timeline" href="https://twitter.com/Marta_catalonia?ref_src=twsrc%5Etfw">Tweets by XDevelopers</a>
    <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

I would like to know if it is possible to show only the lasts 20 tweets

How do I style Javascript output for html?

I’m creating a sign-up page. I use PHP. The PHP has an error code. The error codes are being read by JS. The JS should provide an error message in HTML. The text I get does not have any style.

I would like to be able to style my JS output by CSS. If that is not possible are there any other ways to manage the error messages?

document.addEventListener("DOMContentLoaded", function() {
  // Add event listeners to input fields
  var inputFields = document.querySelectorAll('input');
  inputFields.forEach(function(input) {
    input.addEventListener('input', function() {
      hideError();
    });
  });
});

function submitForm() {
  var name = document.getElementById('name').value;
  var email = document.getElementById('email').value;
  var user_password = document.getElementById('user_password').value;
  var confirm_password = document.getElementById('confirm_password').value;

  var xhr = new XMLHttpRequest();
  var formData = new FormData();

  formData.append('name', name);
  formData.append('email', email);
  formData.append('user_password', user_password);
  formData.append('confirm_password', confirm_password);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText);

      if (response.success) {
        // Redirect to login page or show a success message
        window.location.href = 'Login.html';
      } else {
        // Display error message
        showError(response.error);
      }
    }
  };

  xhr.open('POST', 'create_account.php', true);
  xhr.send(formData);
}

function showError(errorMessage) {
  var errorDiv = document.getElementById('error-message');
  errorDiv.innerHTML = errorMessage;
  var errorStyle = document.getElementById('error-message').style;
}

function hideError() {
  var errorDiv = document.getElementById('error-message');
  errorDiv.innerHTML = '';
}
<div class="container">
  <form action="#" method="post" class="form" id="create_account">
    <h1 class="form__title">Create Account</h1>

    <div class="message">
      <div id="error-message" class="error-message"></div>
    </div>

    <div class="form__input-group">
      <input type="text" class="form__input" autofocus placeholder="Username" name="name" id="name">
    </div>
    <div class="form__input-group">
      <input type="text" class="form__input" autofocus placeholder="E-mail" name="email" id="email">
    </div>
    <div class="form__input-group">
      <input type="password" class="form__input" autofocus placeholder="Password" name="user_password" id="user_password">
    </div>
    <div class="form__input-group">
      <input type="password" class="form__input" autofocus placeholder="Confirm Password" name="confirm_password" id="confirm_password">
    </div>
    <button class="form__button" type="button" onclick="submitForm()">Sign-Up</button>
    <p class="form__text">
      <a class="form__link" href="./Login.html" id="linkLogin"> Already have an account? Sign in! </a>
    </p>
  </form>
</div>

Using laravel, websocket for a real-time chat application, is it a good idea?

I’m in a quite small team that is currently planning on building a real time web application that has a chatbot integrated into it. we’re using laravel as the framework and we’re planning on using websocket as the comunication protocol. what are the drawbacks/trade off that I have to consider?

I heard that its not recomended to use laravel for a websocket-based chat and its better to use NodeJS instead, what do you guys think

thank you in advance and sorry if it sounds weird or anything

How to pass fields values from one form action to another action class method in Struts2 Dynamic Web Project?

I’m very new to Struts2 and facing tons of issues. In my Struts2 Dynamic Web Project, I’m searching an order with order id and then displaying few fields on the UI in editOrder.jsp page after execute() method is executed successfully in my EditOrderWithOrderIdAction class.

In the same jsp page (on the UI), if the user wants to change anything, for e.g., comments field values and then hit on SAVE button, it should invoke another method updateOrderDetails() (in the same action class, EditOrderWithOrderIdAction) which will save the
details into Database table.

How do I preserver and send these various fields values (fetched in first form when clicking SEARCH button) to the second method updateOrderDetails() written in the same action class so that I can use their values to to perform insert or update operation? Anyone please guide me, your help is much appreciated!

Below are my classes and configurations:

struts.xml (firstly, displaying the editOrder jsp page on UI by using url /editOrder and then populating the fields values after execute() method is executed successfully)

<action name="editOrder">
    <result>/editOrder.jsp</result>
</action>

<action name="editOrderWithOrderId" class="com.action.EditOrderWithOrderIdAction"
    method="execute">
    <result name="success">/editOrder.jsp</result>
</action>

editOrder.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Edit Your Order</title>
</head>
<body>
    <!-- User input field to enter the order id to get the order details -->
    <h1>Order Details</h1>
    <s:form action="editOrderWithOrderId" method="post">
        <s:textfield label="Order ID" name="orderId" key="orderId" required="true" />
        <s:fielderror fieldName="orderId" />
        <s:submit value="Search" />
    </s:form>

    <!-- Display the order details when it's available -->
    <s:if test="lpoNumber != null">
        <s:textfield label="LPO Number ID" name="lpoNumber" key="lpoNumber" />
        <s:textfield label="LPO Date" name="lpoDate" key="lpoDate" readonly="true" />
        <s:textfield label="Comments" name="comments" key="comments" />
        <s:select label="Site Address" name="selectedAddress" list="siteAddressList" />
        <s:textfield label="Sales Agent" name="salesAgent" key="salesAgent" />
    </s:if>
    <s:else>
        <p>
            No details found for Order ID: <s:property value="orderId" />
        </p>
    </s:else>
</body>
</html>

EditOrderWithOrderIdAction class:

public class EditOrderWithOrderIdAction {

    private String orderId;
    private String lpoNumber;
    private Date lpoDate;
    private List<String> siteAddressList;
    private String salesAgent;
    private String comments;

    // Getter-Setter of above fields
    
    // Main execute method for displaying the order details
    public String execute() {
        try {
            EditOrderResponse editOrderResponse = someService.getOrderDetailsByOrderId(getOrderId());

            // Set the values to display
            if (!StringUtils.isEmpty(editOrderResponse.getCustLpoNum())) {
                setLpoNumber(editOrderResponse.getCustLpoNum());
                // set remaining other fields
            } else{
                System.out.println("No details found for order id: " + orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
    
    // This method should be invoked when SAVE NOW button is clicked with all fields values coming here
    public String updateOrderDetails() {
        System.out.println("Order Number or ID: " + getOrderId());  // coming as null
        System.out.println("LPO Number: " + getLpoNumber());        // coming as null
        ...
        ...
        ...
        return "success";
    }
}

How are functions and components inside React.StrictMode executed [duplicate]

import React,{useEffect} from 'react';

export function App(props) {
  function run(){
    console.log("run")
  }
  function run2(){
    console.log("run2")
  }
  run2()
  useEffect(()=>{
    console.log("run3");
    return ()=>{
      console.log("run4");
    }
  })
  return (
    <div className='App'>
    {run()}
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

// Log to console
console.log('Hello console')

why does it print
run
run2
run
run2
run3
run4

can someone explain? I wasnt able to find anything regarding this.
Thanks

Not sure how it works

Virtual Trial Room Human Body Creation

I’m a full-stack + AI developer… Was working on a Virtual Try-on Application for my web-based project and came across Zyler.

They detect face and skin color And I’m trying to figure out how they created the avatar like below which can change shape without lags in real time.

enter image description here

Curious to know how they managed to create this avatar and then flawlessly perform pose change for trial.

Would be glad if you could suggest the library they might have used or share the implementation logic/code.

Thanks in advance!

How to write a Javascript regex pattern which test if a string starts with a certain string and has a certain string followed by numbers

How to write the following regex pattern to test below string:

My string: `/my-name/optional-random-string/my-type/354553435/my-random-title

With Javascript regex I want to test a certain pattern:

  • it should start with /my-name
  • it should always have /my-type/6767856874 -> /my-type followed by /random digits

JS: how to handle error from nested then() in outer catch block? [duplicate]

I am following a tutorial about handling errors of fetch() but now it turns to be learning handling errors. This is the code I wrote. I wish to handle all errors inside the outer catch:

        fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: {
        name: this.enteredName,
        rating: this.chosenRating
      }
    }).then(response => {
      if (response.ok) {
        //...
      } else {
        response.json().then(json => {
          const msg = 'Custom error handling: could not save data' +
            ', error code: ' + response.status + ', error: ' + json.error;
          throw new Error(msg);
        }).catch(e => {
          console.log('catch1:');
          throw e;
        });
      }
    })
      .catch(err => {
        console.log('catch2:');
        this.error = err.message;
      });

The problem with this code is that the outer catch cannot catch the error from inner then block, even through I rethrow it in inner catch block. What would be a clean and elegant way to achieve this? Please dont change response.ok because I wish to learn the solution for this exact situation.