Update total in Stripe payments upon shipping rate change (Amazon, Google Pay etc)

Here is some infromation about shippingratechange for Stripe express checkout.
https://docs.stripe.com/js/elements_object/express_checkout_element_shippingratechange_event

which implemented and when the Stripe payment button is clicked the modal window properly displayed:
enter image description here

Then, as you see on the image, there are several shipping options properly passed and rendered. Once another shipping option (with another price) is chosen, it triggers ‘shippingratechange’. How to update the Total because the shipping price was changed?

When I change the shipping option, it changes fine, but the Total remains unchanged, although shippingratechange gets triggered with no questions. How to set another totals value, for example 99.90 (let’s say the math calculated).

What should be added to here?

expressCheckoutElement.on('shippingratechange', function(event) {
  var resolve = event.resolve;
  var shippingRate = event.shippingRate;
  // handle shippingratechange event

  // define payload and pass it into resolve
  var payload = {
    shippingRates: [
      shippingRate
    ]
  };

  // call event.resolve within 20 seconds
  resolve(payload);
});

Why does a small React dynamic import file (~3.7 KB) take 650 ms on first load but only 45 ms on refresh with AWS S3 + CloudFront?

I have a React app deployed on AWS S3 + CloudFront.

One of my routes uses a dynamic import (import()), and the corresponding JS chunk is very small (~3.7 KB).

On the first load, the request for this file takes about 650 ms, but if I refresh the page immediately afterward, it only takes about 45 ms.

Here’s the request and response details from Chrome DevTools for the file:

Request URL: https://admin.simprosysapis.com/assets/RolesList-DVgRFD0k.js
Request Method: GET
Status Code: 200 OK
Remote Address: 18.66.57.77:443
Referrer Policy: strict-origin-when-cross-origin

Response headers

cache-control: max-age=3600, must-revalidate
content-encoding: br
content-type: text/javascript
server: SimprosysAPI
via: 1.1 ...cloudfront.net (CloudFront)
x-cache: Miss from cloudfront

Request headers

accept-encoding: gzip, deflate, br, zstd
cache-control: no-cache
pragma: no-cache
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...

My questions

  1. Why does a 3.7 KB file take ~650 ms to load the first time?

    • Is this mostly TLS/handshake + CloudFront latency rather than file size?
    • Is the x-cache: Miss from cloudfront header responsible?
  2. Why does it become so much faster (~45 ms) on refresh?

    • Is the browser using disk/memory cache or a CloudFront cached copy?
  3. Is there a way to improve the first load time for these small dynamic chunks (e.g., preloading, prefetching, or CloudFront settings)?


What I tried

  • Checked headers: content-encoding: br confirms compression is working.
  • Cache headers look reasonable (max-age=3600).
  • Behavior is consistent across multiple builds.

Expected / Desired

I want to understand if this latency difference is normal for CloudFront + S3 dynamic imports, and whether I can optimize the first-load latency further.

How to achieve an “inset carved” gallery card effect inside an image container with CSS clip-path or masks? [closed]

Reference
my trial

I’m trying to replicate a hero section design where the gallery card looks like it is carved into the main image container (instead of floating on top).

I attempted using an SVG clipPath with an organic shape applied to the .main-image, but the gallery card still appears as a separate overlay. It doesn’t blend with the container as expected.

<div class="organic-gallery">
  <!-- Clip path definition -->
  <svg width="0" height="0">
    <defs>
      <clipPath id="organic-carved-shape" clipPathUnits="objectBoundingBox">
        <path d="M 0.06,0 L 0.94,0 C 0.97,0 1,0.03 1,0.06 L 1,0.94 C 1,0.97 0.97,1 0.94,1 L 0.7,1 C 0.68,1 0.66,0.998 0.64,0.995 L 0.05,0.82 C 0.02,0.815 0,0.8 0,0.78 L 0,0.06 C 0,0.03 0.03,0 0.06,0 Z" />
      </clipPath>
    </defs>
  </svg>

  <div class="gallery-container">
    <!-- Main image background -->
    <div class="main-image">
      <img src="circuit.jpg" class="circuit-bg" />
      
      <!-- floating labels -->
      <div class="feature-label" style="top: 3rem; right: 3rem;">On-Device Analysis</div>
      <div class="feature-label" style="top: 8rem; right: 6rem;">Smart App</div>
    </div>

    <!-- supposed to be carved into the main container -->
    <div class="gallery-card">
      <div class="gallery-images">
        <div class="gallery-item">Thumb 1</div>
        <div class="gallery-item">Thumb 2</div>
      </div>
    </div>
  </div>
</div>
.gallery-container {
  position: relative;
  height: 600px;
}

.main-image {
  position: absolute;
  inset: 0;
  border-radius: 3rem;
  overflow: hidden;
  clip-path: url(#organic-carved-shape);
}

.circuit-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.gallery-card {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 380px;
  padding: 1.5rem;
  border-radius: 2rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(12px);
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}

Current result:
The gallery card simply overlaps the main image.

Expected result:
The gallery card should appear as if it’s part of (or cut into) the main container — following the same organic shape, not just sitting on top.

Question:
What’s the correct way (CSS clip-path, mask, pseudo-elements, or another technique) to make the gallery card look “carved into” the image container?

HTML Canvas lineTo() draws with incorrect y coordinates

Achieving clear lines in HTML canvas requires setting the CSS canvas height and width to be the canvas height and width / device pixel ratio:

this.element.style.height = this.element.height / dpr + "px";
this.element.style.height = this.element.height / dpr + "px";

An unfortunate outcome of this is that the lineTo command will now be incorrect. For example, if I draw a square as:

ctx.lineTo(113.395,54.233);
ctx.lineTo(120.791,54.233);
ctx.stroke();

ctx.lineTo(120.791,54.233);
ctx.lineTo(120.791,46.837);
ctx.stroke();

ctx.lineTo(120.791,46.837);
ctx.lineTo(113.395,46.837);
ctx.stroke();

ctx.lineTo(113.395,46.837);
ctx.lineTo(113.395,54.233);
ctx.stroke();

The result is not square:

enter image description here

Anti-aliasing aside, if we average the placement of each line to its darker side, the width is approximately 7px (correct), while the height is approximately 8px (incorrect).

Does anyone have a solution for this?

What will happen if Node.js cannot read a directory (or a part of a file) due to bad/problematic sectors on disk or corrupted file system?

I want to use the directory- and file-reading functions from 'node:fs' to merge multiple files into one file. For example, I have the following script:

import fs from 'node:fs';
import { readdir, readFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
var myStream = fs.createWriteStream('path/to/output.txt', {flags: 'a'});
var dirPath = 'path/to/mydirectory';
try {
    const entries = await readdir(dirPath, { recursive: true, withFileTypes: true });
    for (const entry of entries) {
        if (entry.isFile()) {
        const myPath = join(entry.parentPath, entry.name);
        const { size } = await stat(myPath);
        const contents = await readFile(myPath);
        myStream.write('<path>' + myPath + '</path>' + '<size>' + size.toString(10) + '</size>n' + contents + 'n');
     }
};
} catch (err) {
    console.error(err);
}; 
myStream.end()

My question is: what will happen if a directory cannot be opened or some part of a file cannot be read (due to bad/problematic sectors on disk, corrupted file system, etc.)? Will the program just freeze, so I will need to terminate it manually? Or only the corresponding file/directory will be skipped? Will the program skip a file in its entirety or only the unreadable part of it? What type of error, if any, will the program report? I have not found any information on this topic. Would it be possible to use Node.js to make the full list of problematic directories and files that are located in a given directory?

How to persist uploaded photos in a multi-step React form across page refresh?

I’m building a multi-step form in React where users can upload photos along with other inputs.

Currently:

I store all the form values in a formData state object.

To persist progress across refreshes, I save formData in localStorage.

Problem:

Uploaded photos are stored using URL.createObjectURL(file).

These object URLs don’t survive a page refresh, so the images are lost even though the rest of the form data is restored from localStorage.

Question:

Is there a way to persist uploaded photos across page refreshes without just dumping everything into localStorage?

What are the common patterns for handling this in React multi-step forms?

Should I use IndexedDB for files?

Should I upload files immediately to a temporary backend storage (and store only the reference in localStorage)?

Or is there another best practice for this use case?

Render Issues within animated PNG inside a SVG

I saw this tutorial that teaches how to do complex multilayer parallax scrolls and implemented on my website. While prototyping I found some weird lines that would appear while manipulating the PNG’s (I know the file size is big, I will fix it later). I thought it could be just some white pixels that just needed to be cleaned, but after cleaning all edges the problem persisted. Any idea why browsers are with this render issue?

https://codepen.io/Ramoses-Hofmeister-Ferreira/pen/wBMWBvZ

I was trying to manipulate some images inside an SVG so I could have a responsive multilayer parallax scroll, yet browsers are rendering strange white lines on the edge of the PNG’s that are inside of the SVG.

HTML:

<body>
    <div class="banner">
        <div id="mountain"></div>
    </div>
</body>

CSS:

body {
    margin: 0;
    background-color: #000000;
}

#mountain {
    width: 100%;
    height: 100vh;
    overflow: hidden;
}

#mountain svg {
    width: 100%;
    height: 100%;
    object-position: center;
}

JS:

function loadSVG() {
    fetch("https://raw.githubusercontent.com/astronaut954/pedro/main/img/parallax_scroll.svg")
        .then(res => res.text())
        .then(svg => {
            const mountain = document.getElementById("mountain");
            mountain.innerHTML = svg;

            const svgEl = mountain.querySelector("svg");
            svgEl.setAttribute("preserveAspectRatio", "xMidYMid slice");

            createWrapper("#layer_1");
            createWrapper("#layer_2");

            setAnimationScroll();
            setCloudAnimation();

        });
}

function createWrapper(layerId) {
    const layer = document.querySelector(`#mountain svg ${layerId}`);
    if (!layer) return;

    const wrapper = document.createElementNS("http://www.w3.org/2000/svg", "g");
    wrapper.setAttribute("id", `${layerId.slice(1)}_wrapper`);

    layer.parentNode.insertBefore(wrapper, layer);
    wrapper.appendChild(layer);
}


loadSVG();

function setAnimationScroll() {
    gsap.registerPlugin(ScrollTrigger);

    let runAnimation = gsap.timeline({
        scrollTrigger: {
            trigger: ".banner",
            start: "top top",
            end: "+=1000",
            scrub: true,
            pin: true
        }
    });

    runAnimation.add([
        gsap.to("#cloud10_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud9_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud8_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud7_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud6_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud5_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud4_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud3_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud2_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud1_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud2b", { y: -1500, duration: 2 }),
        gsap.to("#cloud1b", { y: -1500, duration: 2 }),
        gsap.to("#cloud10", { y: -1500, duration: 2 }),
        gsap.to("#cloud9", { y: -1500, duration: 2 }),
        gsap.to("#cloud8", { y: -1500, duration: 2 }),
        gsap.to("#cloud7", { y: -1500, duration: 2 }),
        gsap.to("#cloud6", { y: -1500, duration: 2 }),
        gsap.to("#cloud5", { y: -1500, duration: 2 }),
        gsap.to("#cloud4", { y: -1500, duration: 2 }),
        gsap.to("#cloud3", { y: -1500, duration: 2 }),
        gsap.to("#cloud2", { y: -1500, duration: 2 }),
        gsap.to("#cloud1", { y: -1500, duration: 2 })
    ])
    .add([
        gsap.to("#layer_1", {
            scale: 1.4,
            x: -250,
            y: 0,
            transformOrigin: "50% 0%",
            duration: 2
        }),
        gsap.to("#layer_2", {
            scale: 1.2,
            transformOrigin: "50% 0%",
            duration: 2
        })
    ]);
}

How can I detect when the AG Grid filter dialog closes?

I have an AG Grid, implemented in React/Typescript. It automatically updates with new data, and the columns have filters. When new data comes in, the grid reloads with the changes, which closes the filter dialog if it’s open. That’s not ideal. It seems like a viable solution would be to track when the dialog is open, and hold off on updates while it’s open. I can track when the filter dialog opens (onFilterOpened), or when it changes (onFilterChanged), but I’m not certain how to detect closing the dialog without making a change by clicking off of it so that I can resume changes.

Here’s the event code (which is basically just console logs right now) based on what an AI model suggested:

const onFilterOpened = () => {
  console.log("Filter opened.");
  setIsFilterDialogOpen(true);
};

const onSortChanged = () => {
  if (gridApiRef.current) {
    columnState.current = gridApiRef.current.getColumnState();
  }
};

const onFilterChanged = (event: { api: GridApi; }) => {
  if (
    event.api.getFilterModel() &&
    Object.keys(event.api.getFilterModel()).length > 0
  ) {
    console.log("Filter dialog is opened");
    setIsFilterDialogOpen(true);
  } else {
    console.log("Filter closed.");
    setIsFilterDialogOpen(false);
  }

  console.log("Filter changed");
};

And set up here:

<AgGridReact  
  className={"ag-theme-astro"}  
  columnDefs={colDefGrouped}  
  defaultColDef={defaultColDef}  
  rowData={groupedRowData}  
  domLayout="autoHeight"  
  pagination={true}  
  paginationPageSize={20}  
  isFullWidthRow={isFullWidthRow}  
  fullWidthCellRenderer={fullWidthCellRenderer}  
  getRowHeight={getRowHeight}  
  onGridReady={onGridReady}  
  onFilterChanged={onFilterChanged}
  onFilterOpened={onFilterOpened}
  data-testid="groupedGrid"
/>

I get the “Filter opened” message when it opens, and “Filter dialog is opened” as I type in changes in the filter. But nothing when it closes.

unable to get a hard-coded svg line on d3 chart

I’m trying to just get a simple line on a D3 chart without using an array of data (that will be the next step).

The x-axis is years from 2007 to 2023. The y-axis is numbers from 0.00 to 0.50.

I assume the data pairs I’ll need will be x in a time formatted year and y as a number.

But when I put in the code to draw a line from one point to the other on the chart, nothing appears and I get no error message.

<div id="container"></div>
<script type="module">

const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;

//x-axis is years
const x = d3.scaleUtc()
    .domain([new Date("2007-01-01"), new Date("2023-01-01")])
    .range([marginLeft, width - marginRight]);

//y-axis is numbers between 0 and .5
const y = d3.scaleLinear()
    .domain([0, .5])
    .range([height - marginBottom, marginTop]);

const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x)
        .ticks(d3.utcYear.every(1))
);
    
svg.append("text") //label
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height - 6)
    .text("Year");

svg.append("text") //label
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("x", -height/3)
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("Percent");

svg.append("g")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y));

const parseTime = d3.utcFormat("%Y");

svg.append("line")          // nothing appears
.style("stroke", "black")  
.attr("x1", parseTime(new Date("2007")))     // x position of the first end of the line
.attr("y1", 0.50)      // y position of the first end of the line
.attr("x2", parseTime(new Date("2008")))      // x position of the second end of the line
.attr("y2", 0.40);

container.append(svg.node());

Data from html disappears and doesn’t not post using rest api call. When submit button is selected the form clears and data is not submitted

I have a basic HTML form that submits data to a SharePoint list. There are no errors in the code, nor do I receive anything that would cause the form not to submit to the SharePoint list. I am using basic HTML, some CSS, and AngularJS. The angular code uses a basic rest api call to post the data when the button is selected.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
    <link rel="stylesheet" href="calendar.css">
    <!-- <title>Document</title> -->
</head>
<body>

    <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <div class="form-container">
          <h2 class="text-center" style="font-weight: bold;">Tour Request Form</h2>
          <form action="#" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <div ng-controller="calendarController as calendar">
              <label for="tourRequest">Tour Request</label>
                    <input type="text" class="form-control" id="tourRequest" name="tourRequest" required>
                    <input class="btn-primary" type="submit" value="add">


            </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    </div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="calendar.js"></script>
</body>
</html>
angular.module('mcalendarapp', [])
  .controller('myController', function($scope, $http) {
    $scope.newItem = {
      Title: $scope.tourRequest, // Example: A field in your SharePoint list
     // Description: '' // Example: Another field
    };

    $scope.addItem = function() {
      var listName = 'TourRequest'; // Replace with your list name
      var apiUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listName + "')/items";

      var dataPayload = {
        '__metadata': {
          'type': 'SP.Data.' + listName + 'ListItem' // Adjust if your list name has spaces or special characters
        },
        'Title': $scope.newItem.Title,
       // 'Description': $scope.newItem.Description
      };

      $http({
        method: 'POST',
        url: "/_api/web/lists/getByTitle('mylist')/items",
        headers: {
          'Accept': 'application/json; odata=verbose',
          'Content-Type': 'application/json; odata=verbose',
          'X-RequestDigest': jQuery('#__REQUESTDIGEST').val() // Get the request digest
        },
        data: JSON.stringify(dataPayload)
      }).then(function(response) {
        // Success handling
        alert('Item added successfully!');
        $scope.newItem = {}; // Clear the form
      }).catch(function(error) {
        // Error handling
        console.error('Error adding item:', error);
        alert('Failed to add item. Check console for details.');
      });
    };
  });

Assistance with code and reasoning behind the api call failing

image map with random image on page load

Alright so this is the code i’m using for this section.

<div class="center">
<div class="imgcenter">
 <img id= "myRandomImg" usemap="#map" width="100%" height="100%">

<map name="map">
    <area shape="rect" coords="952,428,1203,657" alt="recent release" href="https://www.google.com">
</map>

<script>
myarray = ["webite1.png", "webite2.png", "webite3.png", "webite4.png", "webite5.png", "webite6.png"]
window.onload = function(){
 var randomNum = Math.floor(Math.random() * 6);
 var randomImgSrc =document.getElementById("myRandomImg").src = myarray[randomNum]; 
 console.log(randomNum)
}
</script>


How to set this image map on the photos being generated when the page loads?

All of the photos are the same size. I’m pretty new to this.

Trouble embedding SSRS report in iframe – scripts fail to load from correct origin

I’m having trouble embedding an SSRS report in an from an external application. The app calls the report server URL, and we’ve already configured CORS and switched to basic authentication.

We pass the credentials in the request using JavaScript, and it seems to work — the report loads the parameter header without prompting for login. However, the page fails to load completely because the Sys scripts throw errors. The issue is that the loaded page tries to fetch scripts from the iframe’s origin (http://192.168.1.101:8081) instead of the SSRS server (http://192.168.1.101), resulting in Uncaught ReferenceError: Sys.

Interestingly, if I embed the iframe without passing credentials and manually authenticate when prompted by the browser, the report loads perfectly.
Below is the JavaScript code used to embed the iframe and the error message. Any suggestions or workarounds would be greatly appreciated!

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Report Viewer</title>
<style>
    body, html {
        margin: 0;
        padding: 0;
        height: 100%;
    }
    iframe {
        width: 100%;
        height: 100%;
        border: none;
    }
</style>
</head>
<body>
<iframe id="reportFrame"></iframe>

<script>
    const username = "user";
    const password = "password";

    const reportUrl = "http://192.168.1.101:80/ReportServer/Pages/ReportViewer.aspx?/MyReport&rs:Embed=True&rc:LinkTarget=main";

    const credentials = btoa(username + ":" + password);

    fetch(reportUrl, {
        method: "GET",
        headers: {
            "Authorization": "Basic " + credentials,
            "Upgrade-Insecure-Requests": "1",
            "Cache-Control":"max-age=0",
            
            "Access-Control-Allow-Origin":"http://192.168.1.101:8081",
            "Access-Control-Allow-Credentials":"true",
            "Access-Control-Allow-Methods":"GET, PUT, POST, PATCH, DELETE",
            "Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization",
        }
    })
    .then(response => response.text())
    .then(html => {
        const iframe = document.getElementById("reportFrame");
        const blob = new Blob([html], { type: "text/html" });
        iframe.src = URL.createObjectURL(blob);
    })
    .catch(error => {
        console.error("Error to load the report:", error);
    });
</script>

Browser Error

We’re using the latest PBI Reporting Server.

unable to adjust d3 y-axis label position

I want to vertically center the y-axis label on a d3 graph. Right now, I have the label at the top of the y-axis. When I try to adjust the y or dy attributes, the label moves horizontally, not vertically. I suspect this has to do with the label being rotated, but when I comment out the rotation, the label disappears.

<div id="container"></div>
<script type="module">

const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;

const x = d3.scaleUtc()
    .domain([new Date("2007-01-01"), new Date("2023-01-01")])
    .range([marginLeft, width - marginRight]);

const y = d3.scaleLinear()
    .domain([0, .5])
    .range([height - marginBottom, marginTop]);

const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x)
        .ticks(d3.utcYear.every(1))
);
    
svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height - 6)
    .text("Year");

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6) //if I change this value, the label moves horizontally
    .attr("dy", ".75em") //if I change this value, the label moves horizontally
    .attr("transform", "rotate(-90)") //if I comment this out, the label disappears
    .text("Percent");

svg.append("g")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y));

container.append(svg.node());

Over riding a forms Submit button with Javascript

I have a login form with a submit button to submit the form. it ‘Fetches’ a PHP page that sets some SESSION Variables and returns to the login screen.
on completion I hide the Login Name and Password inputs and change the value of the Login button to ‘Logout’. I have a JQuery .click function to ‘Fetch’ a PHP page to unset the SESSION vars. However, now the form doesn’t submit. I assume the .click() function on the button is causing this?
How can I successfully overide the submit?

code below:

HTML

    <input
        class="btn"
        id="loginBtn"
        type="submit"
        value="Login"
    />

Javascript:

$("#loginBtn").click(function () {
    if ($("#loginBtn").value != "Logout") {
    return;
    }
    else {
        fetch("./logout.php")
        .then((response) => response.text())
        .then(window.location.replace("./login.html"))
        .catch((error) => console.error("Error:", error));
        }
});

Ive searched high and low but can’t understand a solution.
I could create a new button outside of the form and make that visible when required but thats giving in….