Promise/then for array of functions

I have an array of functions such as:

let funcs = []
funcs.push(() => {window.x = fetch()})
funcs.push(() => {console.log(window.x)})
funcs.push(() => {console.log("Hello, world!")})

I would like the functions to be evoked one after the other, as in:

for (let func of funcs) {
  func();
}

However, I would like to concatenate the functions as if they were Promises so that the N+1 function is only ever invoked when the N function is resolved.

React Paginate Active class not working when i use filter or search list using react and next js

`import { useState, useEffect, forwardRef, useImperativeHandle } from "react";
import { Filter } from "../common/filters/Filter";
import CardList from "./CardList";
import ReactPaginate from "react-paginate";
import courseApiService from "@/services/courseServices";

export const CourseList = forwardRef(
  ({ courseList, trainingList, vendorList }, ref) => {
    CourseList.displayName = "CourseList"; // Add display name
    const [listCourse, setListCourse] = useState(courseList);
    const [pageCount, setPageCount] = useState(0);
    const [selectedTrainings, setSelectedTrainings] = useState([]);
    const [selectedVendors, setSelectedVendors] = useState([]);
    const [query, setQuery] = useState("");
    const [currentPage, setCurrentPage] = useState(1); // current active page

    useImperativeHandle(ref, () => ({
      courseListApi,
    }));

    const limit = 2;
    const vendorQueryString = selectedVendors
      .map((id) => `vendors[]=${id}`)
      .join("&");
    const trainingQueryString = selectedTrainings
      .map((id) => `trainings[]=${id}`)
      .join("&");

    console.log(vendorQueryString);
    console.log(trainingQueryString);


    useEffect(() => {

      courseListApi(1, "", vendorQueryString, trainingQueryString);
    }, [selectedTrainings, selectedVendors]);

    function handleTrainingsSelection(selectedItems) {
      setSelectedTrainings(selectedItems);
    }

    function handleVendorsSelection(selectedItems) {
      setSelectedVendors(selectedItems);
    }
    const courseListApi = async (
      currentPage,
      query,
      vendorQueryString = "",
      trainingQueryString = ""
    ) => {
      setQuery(query);
      try {
        const fetchedCourses = await courseApiService.getCourses(
          currentPage,
          limit,
          query,
          trainingQueryString,
          vendorQueryString
        );
        setListCourse(fetchedCourses);

        const total = fetchedCourses?.count;

        setPageCount(+Math.ceil(total / limit));

        setCurrentPage(currentPage);
        console.log(listCourse);
      } catch (error) {
        console.log(error);
      }
    };
    console.log(currentPage);
    const nextPageClick = async (data) => {
      console.log(data.selected);
      let currentPage = data.selected + 1;

      setCurrentPage(currentPage);

      await courseListApi(
        currentPage,
        query,
        vendorQueryString,
        trainingQueryString
      );
    };

    return (
      <div>
        <div className="flex gap-[2.4rem] xl:px-[6.4rem] small:px-[3.4rem] mt-[4.8rem] ">
          <div className="hidden lg:block">
            <Filter
              vendor={vendorList}
              training={trainingList}
              handlePageClick={courseListApi}
              onTrainingsSelection={handleTrainingsSelection}
              onVendorsSelection={handleVendorsSelection}
              selectedVendors={selectedVendors}
              selectedTrainings={selectedTrainings}
            />
          </div>

          <div className="flex flex-col justify-between">
            <div>
              <CardList
                vendor={vendorList}
                training={trainingList}
                handlePageClick={courseListApi}
                onTrainingsSelection={handleTrainingsSelection}
                onVendorsSelection={handleVendorsSelection}
                name={listCourse}
              />
            </div>
            <div className="mt-[2rem] mb-[2rem]">
              <ReactPaginate
                breakLabel="..."
                nextLabel=" > "
                onPageChange={nextPageClick}
                pageCount={pageCount}
                previousLabel="< "
                previousClassName="bg-bg_grey  rounded-full p-[1rem] text-gray_800"
                nextClassName="bg-bg_grey  rounded-full p-[1rem] text-gray_800"
                containerClassName="flex text-center gap-[1.2rem] w-[100%]  text-s16  items-center leading-[1rem] font-semibold"
                pageClassName="w-[3.2rem] h-[3.2rem] p-[1rem] text-center flex "
                pageLinkClassName="text-s18  "
                renderOnZeroPageCount={null}
                activeClassName="bg-hero_bg hover:bg-hero_bg cursor:pointer text-main rounded-full"
            
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
);

````your text`
type here

when i filter the list it updates the list but active class doesnot get updated e.g i get list with 3 pages when i paginate to 3rd page it works well and active class also updates which shows on which page u are and then i use filter it fetches data correctly and also no. of pages bur active class will remain on page 3 and will not be displayed i use force page and initial page also but it doesnot work `

Hash is storing in the blockchain

Actually i’m very new to the blockchain world. And i’m trying to build the Certificate validation system. I wrote the smart contract and connected this using webjs. Im using Truffle and ganache for testing the project.
When user has to upload the certificate and hash of that certificate is storing in the blockchain.I add the functionality that if the hash of that certificate is already present in the blockchain.It has to refuse the certificate saying Certificate is already in the blockchain.
It displaying the error but the hash is storing in the blocks.
I dont want to store the hash again if it is already present in the blockchain.

Smart contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title CertificateValidation
 * @dev A smart contract for validating certificates using SHA256 hashes.
 * @custom:dev-run-script deploy
 */
contract CertificateValidation {
    event CertificateAdded(bytes32 hash);
    bytes32[] certificates;
    mapping (bytes32 => mapping(address => bool)) private certificateHashes;

    function addCertificate(bytes32 hash) public payable {
 
   if (certificateHashes[hash][msg.sender]) {
        revert("Certificate hash already submitted ");
    }
    for (uint i = 0; i < certificates.length; i++) {
        if (certificates[i] == hash) {
            revert("Certificate hash already exists");
        }
    }

        certificateHashes[hash][msg.sender] = true;
        certificates.push(hash);
        emit CertificateAdded(hash);
    }
   
    function verifyCertificate(bytes32 hash) public view returns (bool) {
        for (uint i = 0; i < certificates.length; i++) {
            if (certificates[i] == hash) {
                return true;
            }
        }
        return false;
    }
}

Web3js code

const web3 = new Web3("HTTP://127.0.0.1:7545");

import MyContractABI from "../build/contracts/CertificateValidation.json" assert { type: "json" };
const abi = MyContractABI.abi;
const address = "0x76daA4B119FB7EcdeCF9318f60AbDc0B69ed5673";
const certificateValidationContract = new web3.eth.Contract(abi, address);

async function connectMetamask() {
  const web3 = new Web3(window.ethereum);
  // ...
  const walletAddress = await web3.eth.requestAccounts();
  console.log(walletAddress);
  const walletBal = await web3.eth.getBalance(walletAddress[0]);
  const walletBalinEth = Math.round(web3.utils.fromWei(walletBal, "ether"));
  console.log(walletBalinEth);
}

connectMetamask();

async function verifyCertificate() {
  const certificateFile = document.getElementById("certificate-verify-file")
    .files[0];
  const certificateHash = await calculateHash(certificateFile);
  console.log(certificateHash);
  const certificateIsValid = await certificateValidationContract.methods
    .verifyCertificate(certificateHash)
    .call();
  const resultElement = document.getElementById("result");
  if (certificateIsValid) {
    resultElement.innerText = "Certificate is valid";
  } else {
    resultElement.innerText = "Certificate is not valid";
  }
}
async function uploadCertificate() {
  console.log("Control is here");
  const certificateFile = document.getElementById("certificate-add-file")
    .files[0];
  const certificateHash = await calculateHash(certificateFile);
  console.log(certificateHash);
  const status = await storeCertificateHashOnBlockchain(certificateHash);
  if (status) {
    alert("Certificate uploaded successfully!");
  }
}

async function calculateHash(file) {
  const fileBuffer = await file.arrayBuffer();
  const certificateHashBuffer = await crypto.subtle.digest(
    "SHA-256",
    fileBuffer
  );
  const certificateHashArray = Array.from(
    new Uint8Array(certificateHashBuffer)
  );
  const certificateHashHex = certificateHashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return "0x" + certificateHashHex;
}

async function storeCertificateHashOnBlockchain(certificateHash) {
  const accounts = await web3.eth.getAccounts();
  try {
    await certificateValidationContract.methods
      .addCertificate(certificateHash)
      .send({
        from: accounts[2],
        gas: 300000,
        value: web3.utils.toWei("0.001", "ether"),
      });
    return true;
  } catch (error) {
    console.error(error);
    alert("Certificate already exists on the blockchain.");
    
    return false;
    
  }
}

const uploadBtn = document.getElementById("upload_certificate");
uploadBtn.addEventListener("click", uploadCertificate);

async function storeCertificateHashOnBlockchain(certificateHash) {
  const accounts = await web3.eth.getAccounts();
  try {
    await certificateValidationContract.methods
      .addCertificate(certificateHash)
      .send({
        from: accounts[2],
        gas: 300000,
        value: web3.utils.toWei("0.001", "ether"),
      });
    return true;
  } catch (error) {
    console.error(error);
    alert("Certificate already exists on the blockchain.");
    
    return false;
    
  }
}

By the suggestion on chatGPT i tried the return statement which will forcefully stop the execution.But it didnt work…

How read .conf files from NodeJS?

Good time, there was a need to read the .conf file to pull out the values from there in saw VARIABLE = ‘value’, how can this be implemented?
The file itself also contains comments that I would like to ignore and find only the necessary values.

I tried to read the file linearly and knowing the line variables, read it

SignalR client try to run on the server side NodeJS

I am trying to run Signalr client on the server side NodeJS. but i am getting bellow error. how can i resolve this issue?
Chat.js code

const signalR = require("@microsoft/signalr");

const connection = new signalR.HubConnectionBuilder()
  .withUrl("http://127.0.0.1:7265/chathub")
  .configureLogging(signalR.LogLevel.Information)
  .build();

const start = async () => {
  try {
    await connection.start();
    console.log("Connected to signal r hub");
  } catch (error) {
    console.log(error);
  }
};
// starting the app
const startApp = async () => {
  await start(); // connection will stablised
};

startApp();

I am getting error

[2023-04-08T07:27:03.490Z] Error: Failed to complete negotiation with the server: FetchError: request to http://127.0.0.1:7265/chathub/negotiate?negotiateVersion=1 failed, reason: connect ECONNREFUSED 127.0.0.1:7265
[2023-04-08T07:27:03.490Z] Error: Failed to start the connection: Error: Failed to complete negotiation with the server: FetchError: request to http://127.0.0.1:7265/chathub/negotiate?negotiateVersion=1 failed, reason: connect ECONNREFUSED 127.0.0.1:7265
FailedToNegotiateWithServerError: Failed to complete negotiation with the server: FetchError: request to http://127.0.0.1:7265/chathub/negotiate?negotiateVersion=1 failed, reason: connect ECONNREFUSED 127.0.0.1:7265
    at HttpConnection._getNegotiationResponse (/Users/user/Desktop/WebChat-Client-master/node_modules/@microsoft/signalr/dist/cjs/HttpConnection.js:256:35)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async HttpConnection._startInternal (/Users/user/Desktop/WebChat-Client-master/node_modules/@microsoft/signalr/dist/cjs/HttpConnection.js:172:41)
    at async HttpConnection.start (/Users/user/Desktop/WebChat-Client-master/node_modules/@microsoft/signalr/dist/cjs/HttpConnection.js:75:9)
    at async HubConnection._startInternal (/Users/user/Desktop/WebChat-Client-master/node_modules/@microsoft/signalr/dist/cjs/HubConnection.js:132:9)
    at async HubConnection._startWithStateTransitions (/Users/user/Desktop/WebChat-Client-master/node_modules/@microsoft/signalr/dist/cjs/HubConnection.js:109:13)
    at async start (/Users/user/Desktop/WebChat-Client-master/chat.js:10:5)
    at async startApp (/Users/user/Desktop/WebChat-Client-master/chat.js:18:3) {
  errorType: 'FailedToNegotiateWithServerError'
}

Subscriber is running multiple times ,even if we unsuscribed it

file name :- brief-component.ts
I am calling drawer service like
this.assignDrawerService.showDrawer(parameter);

file name:- drawer-service.ts

 private drawerSubject = new BehaviorSubject<boolean>(false);
    public drawer$: Observable<boolean> = this.drawerSubject.asObservable();

 public showDrawer(viewType:any) {
        this.drawerSubject.next(viewType);
        }

file name :- drawer-component.ts

Debugger hitting multiple times

this.assignDrawerService.drawer$.subscribe(viewType => {
      debugger
});

I am expecting subscriber should run once .
I tried takeUntil , unsuscribe , first

Function is not defined on callbackFinished (winwheel library)

When I try to call a function with the callbackFinished property inside the animation of winwheel I get function is not defined while it’s defined on the same class.

import React from 'react'
import Winwheel from 'winwheel'
import TweenMax from 'gsap'

const Roulette = ({ width, height, canvasId,}) => {
    let winWheel = null

    const wheelData = {}

    const animation = {
            'type': 'spinToStop',
            'duration': 5,
            'spins': 8,
            'easing': 'Power2.easeInOut',
            'callbackFinished': 'alertPrize()' //Error here, can't get alertPrize() function
    }

    wheelData['animation'] = animation
    
    function alertPrize()
    {
        createWheel()
        // Call getIndicatedSegment() function to return pointer to the segment pointed to on wheel.
        let winningSegment = winWheel.getIndicatedSegment();
        // Basic alert of the segment text which is the prize name.
        alert("You have won " + winningSegment.text + "!");
    }

    const startAnimation = () => {
        winWheel = null
        createWheel()
        winWheel.startAnimation()
    }

    const createWheel = () => {
        if (typeof window !== 'undefined' && winWheel == null) {
            winWheel = new Winwheel(wheelData)
        }
    }

    createWheel()

    return (
        <div>
            <canvas id={canvasId} width={width} height={height} className='z-0'>
                Canvas not supported
            </canvas>
            <button onClick={startAnimation} className='absolute w-full h-full top-0'></button>
        </div>
    )
}

Any way of getting the function on callbackFinished?

Trouble writing a span to a pdf with pypdf

I am using pypdf python library to create a way to lock a pdf to only one mac address. So that only one person can open the pdf and after that it will be locked, it won’t be able to open on other devices. But I am having trouble writing the mac address of the device to the span. what am I doing wrong? Here is my code:

import os
import subprocess
import pypdf
import uuid

# Get MAC address of device
mac_address = hex(uuid.getnode())

# Create JavaScript to be embedded in PDF
js_code = f""" 
var mac_address_span = this.getField("mac-address");
if (mac_address_span == null) {{
    var new_span = this.addField("mac-address", "int", {mac_address}, [0, 0, 0, 0]);
    
    app.alert("MAC address span created with value: " + {mac_address});    
}} else {{
    app.alert('whyyy2');
    if (mac_address_span.get("/V") == "{mac_address}") {{
        app.alert("MAC address span exists with matching value: " + mac_address_span.value);
    }} else {{
        app.alert("MAC address span exists with non-matching value: " + mac_address_span.value);
        this.closeDoc(true);
    }}
}}
"""

# Open PDF
with open("example.pdf", mode="rb") as f:
    pdf_reader = pypdf.PdfReader(f)
    pdf_writer = pypdf.PdfWriter()

 
    # Add JavaScript action to document open event
    js_name = 'mac-address.js'
    js_action = pdf_writer.add_js(js_code)
    
    if js_action:
        pdf_writer._add_object(js_action)
    else:
        print("Failed to create JavaScript action object")


    # Add all pages to output PDF
   # for page in range(pdf_reader.pages()):
    #    pdf_writer.addPage(pdf_reader.getPage(page))

    for page in range(len(pdf_reader.pages)):
        pdf_writer.add_page(pdf_reader.pages[page])

    # Save output PDF
    with open("output.pdf", mode="wb") as output_file:
        pdf_writer.write(output_file)

# Open output PDF
if os.name == 'nt':  # for Windows OS
    os.startfile("output.pdf")
else:  # for Mac OS
    subprocess.call(["open", "output.pdf"])

Tauri notification doesn`t appear

I have tauri problem. When I use function sendNotification it doesn`t do anything.

Main.jsx file. Here I listen for event “show_notification”. I am sure that it works because I tried to log payload when event emitted from backend. Also I need to writeText to clipboard but It also doesn`t work.

Handlers.rs file. Here function notification waits for request and then it send event to frontend with message payload.

Code:

Main.jsx

import { invoke } from "@tauri-apps/api";
import { listen } from "@tauri-apps/api/event";
import {
  isPermissionGranted,
  sendNotification,
  requestPermission,
} from "@tauri-apps/api/notification";
import { readText, writeText } from "@tauri-apps/api/clipboard"

if (process.env.NODE_ENV === "production") {
  invoke("plugin:autostart|enable");
}

readText().then((response) => console.log(response));

useEffect(() => {
    const unlisten = listen("show_notification", (ev) => {
      sendNotification({ title: "INotifyer", body: ev.payload });
    });

    listen("set_clipboard", (ev) => {
      writeText(ev.payload);
    });

    return () => {
      unlisten.then((f) => f());
    };
  }, []);

Handlers.rs

pub async fn notification(
    action: models::Action,
    window: tauri::Window
) -> Result<impl Reply, Infallible> {
    window.emit("show_notification", action.msg.to_string()).unwrap();
    Ok(warp::http::StatusCode::OK)
}

Configuration

tauri.conf.json

"tauri": {
    "allowlist": {
      "all": false,
      "clipboard": {
        "all": true
      },
      "notification": {
        "all": true
      }
    },
    "bundle": {
      "active": true,
      "category": "DeveloperTool",
      "copyright": "",
      "deb": {
        "depends": []
      },
      "externalBin": [],
      "icon": [
        "icons/32x32.png",
        "icons/128x128.png",
        "icons/[email protected]",
        "icons/icon.ico"
      ],
      "longDescription": "",
      "macOS": {
        "entitlements": null,
        "exceptionDomain": "",
        "frameworks": [],
        "providerShortName": null,
        "signingIdentity": null
      },
      "resources": [],
      "shortDescription": "",
      "targets": "all",
      "windows": {
        "certificateThumbprint": null,
        "digestAlgorithm": "sha256",
        "timestampUrl": ""
      }
    },
    "security": {
      "csp": null
    },
    "windows": [
      {
        "fullscreen": false,
        "height": 600,
        "resizable": false,
        "title": "INotifyer",
        "width": 1000,
        "decorations": false,
        "transparent": true,
        "visible": false
      }
    ],
    "systemTray": {
      "iconPath": "icons/32x32.png",
      "iconAsTemplate": true
    }
  }

Cargo.toml

tauri = { version = "1.2.3", features = ["clipboard-all", "devtools", "notification-all", "system-tray"] }
tauri-plugin-single-instance = { git = "https://github.com/tauri-apps/tauri-plugin-single-instance", branch = "dev" }
tauri-plugin-autostart = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "dev" }

Package.json

"scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "tauri": "tauri",
    "start": "tauri dev"
  },
  "devDependencies": {
    "@tauri-apps/api": "^1.2.0",
    "@tauri-apps/cli": "^1.2.3",
    "@types/react": "^18.0.32",
    "@types/react-dom": "^18.0.11",
    "@vitejs/plugin-react": "^3.1.0",
    "react-error-overlay": "^6.0.11",
    "sass": "^1.60.0",
    "vite": "^4.2.1"
  },
  "dependencies": {
    "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
    "@react-icons/all-files": "^4.1.0",
    "@tauri-apps/api": "^1.2.0",
    "animejs": "^3.2.1",
    "firebase": "^9.19.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.8.0",
    "react-router-dom": "^6.10.0",
    "vite-plugin-require": "^1.1.10"
  }

Platform

OS: Windows 11

How to show Custom text by selected variation name woocommerce?

want to display custom text when i select variation name. Like if i select GOOD custom text is–> it’s Moderately used. , or if select VERY GOOD custom text is –> Minimally used.

need help from jquery or JavaScript help.

i tried by using switching case but it’s not working automatically just works for select variation. when i change variation it’s not working.

function display_products_attribute_description() {
   global $product;
     foreach ( $product->get_visible_children() as $variation_id ) {

     $get_product_variation = wc_get_product( $variation_id );

     $product_variation_stock = $get_product_variation->get_attribute('aesthetic-condition');

        switch ( $product_variation_stock ) {
            case 'Good':
                $text = __( '

<div class="aest-cond-def"><span class="aest-cond-title">Good: </span>Moderately used.</div>

        ' );
                break;
            case 'Very Good':
                $text = __( '
                    <div class="aest-cond-def"><span class="aest-cond-title">Very Good: </span><p>Minimally used.</p></div>
' );
break;
}
        return $text;
    }
}

Web-scraping data from a built in Java script game

Essentially, I’m using Python to try and get the score of a java script game built into a website.

I’ve used Tesseract and Selenium so far to try and screenshot and recognise the score but I need consistency and it does stuff up the numbers sometimes. I’ve also tied changing Tesseract’s page segmentation modes and it did improve slightly but still not giving exact numbers. For example it gives 33.7 instead of 38.7 or even = and _ symbols as the score changes.

My entire code is a bit long but in essence it takes a screenshot after each press of a key (to move the character), then displays the score. This is an example of just the screenshotting I have.

from selenium import webdriver
from pytesseract import pytesseract
from PIL import Image
import time

drvGame = webdriver.Chrome(executable_path=r"C:Program Fileschromedriver.exe")
pthTesseract = r"C:Program FilesTesseract-OCRtesseract.exe"
pthImage = r"scrOriginal.png"
pytesseract.tesseract_cmd = pthTesseract

drvGame.get("https://www.foddy.net/ice/")
drvGame.set_window_size(width = 1000, height = 536)
time.sleep(10)
drvGame.save_screenshot("scrOriginal.png")

imgScore = Image.open(pthImage)
width, height = imgScore.size
box = 850, 0, width, height / 5

imgCropped = imgScore.crop(box)
imgCropped.save("scrCropped.png")

fltScore = pytesseract.image_to_string(imgCropped, config = "--psm 7")
fltScore = fltScore.replace("n", "")
    
print (fltScore)

For context the website is ‘https://www.foddy.net/ice/’ and the script in the HTML source is titled ‘./surprise.min.js’. An ‘imgCropped’ example looks like this.

I’m new to web-scraping and Selenium in general so anything to help would be appreciated.

Add list of text on same background image automatically by downloading all the images one by one

I have the following list of text which I want to add to the images and then a list of image names by which I want to save them. I have written the following code but I don’t understand how I proceed. In the following code when on the 1st textarea, list of text is pasted then in the 2nd textarea images names are pasted. Now when in the 2nd textarea on input pasting image names the function as to perform. This function will get one by one text from text list which divided by line breaks add it on the image background then download image based on 2nd textarea names provided. So basically it takes 1st line from 1st textbox and 1st line from 2nd textbox so on. My following code is adding and downloading the edited image but only at once.

List of text to Add:
Earn
Stay
Find
Succeed

List of Image names:
Spend
Leave
Lose
Fail

Code

function myFunction1() {
  
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = document.getElementById("image1").width;
canvas.crossOrigin = "Anonymous";
canvas.height = document.getElementById("image1").height;
ctx.drawImage($('#image1').get(0), 0, 0);
ctx.font = "40pt Segoe UI Black";



}
  
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = document.getElementById("image1").width;
canvas.crossOrigin = "Anonymous";
canvas.height = document.getElementById("image1").height;
ctx.drawImage($('#image1').get(0), 0, 0);
ctx.font = "40pt Segoe UI Black";


function myFunction() {
 
$(document).on('input','#listOfNames',function(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.drawImage($('#image1').get(0), 0, 0);
    ctx.fillStyle = "white";
    
    ctx.textBaseline = 'middle'; 
ctx.textAlign = 'center'; 

ctx.fillText($(this).val(), 600/2, 600/2);
    
    downloadImage();
    
});
$('button').click(function(){
    console.log(ctx.getImageData(50, 50, 100, 100));
});
  
  }
  
function downloadImage()
{
var canvas = document.getElementById("canvas");
    image = canvas.toDataURL("image/png", 1.0).replace("image/png", "image/octet-stream");
  var link = document.createElement('a');
  link.download = "Good Morning Image 1.png";
  link.href = image;
  link.click();
  }
<script src="https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <head>
 
 </head><body onload="myFunction1()">

<form>
<center>

<b>List Of Text:</b><br><br>
<textarea id="listOfText" style="width:100%;" rows="10" cols="50"></textarea><br><br>

<b>List Of Image Names:</b><br><br>
<textarea id="listOfNames" oninput="myFunction()" style="width:100%;" rows="10" cols="50"></textarea><br><br>

<canvas height="200" id="canvas" style="border: 2px solid blue;height: 200px;"></canvas><br>
<img id="image1" style="display:none" src="https://i.imgur.com/ItiMbDZ.jpg" crossorigin="anonymous"/>

</center>
</form>


</div>

Frontend HTML refreshes after a POST request, updated elements will go back to being what they were previously

I use FastAPI with Python to run the backend of the server. I am trying to connect the local frontend client with the local backend server. I am able to submit a POST request and the server, the server is being updated with new data (URL, password, shortened URL). I use axios() to POST my request, and use .then to get the response and update selected element.

My issue comes from the frontend receiving the data, then updating my <h1> element and console.log() the JSON data before immediately refreshing, removing or undoing all changes.

Server
POST: http://127.0.0.1:8000/url

My frontend portion

    <form id="myForm">
        <label for="inputField">Enter your URL:</label>
        <input type="text" id="inputField" name="url" required>
        <button type="submit">Submit</button>
    </form>
    <h1 id="short_url"></h1>

    <script>
        const form = document.getElementById("myForm");
        form.addEventListener("submit", async (event) => {
            event.preventDefault();
            const formData = new FormData(form);
            const longURL = formData.get("url");
            axios
                .post(
                    "http://127.0.0.1:8000/url",
                    { target_url: longURL },
                    {
                        headers: {
                            "Content-Type": "application/json",
                        },
                    }
                )
                .then(function (response) {
                    console.log(response.data.admin_url);
                    document.getElementById("short_url").textContent = response.data;
                });
        });
    </script>

My backend portion where the POST request happens

@app.post("/url", response_model=schemas.URLInfo)
def create_url(url: schemas.URLBase, db: Session = Depends(get_db)):
    if not validators.url(url.target_url):
        raise_bad_request(message="Your provided URL is not valid")

    db_url = crud.create_db_url(db=db, url=url)
    return get_admin_info(db_url)

I have tried using return false at the end of frontend, using fetch() instead of axios(), expecting the update to stick but result is still the same, instant refresh of less than 1~5 seconds.

I have also tried using setTimeout(), but the speed at which it refresh is still the same.

What was successful was purposefully causing an error, it would no longer refresh but immediately following that, if I add in a proper URL, it would refresh the whole webpage.

Lastly, I have checked my database every POST request and it is constantly being updated with new data that I input.

Thank you in advance.

How can I access this property in an object

I’m returning an object that has a key defined like this template[body]. Here is an example of the returned object:

object = {
 method: 'patch',
 authentication_token: 'a string',
 template[body]: 'another string',
 ...
}

How can I access the second value? I’m doing something like object.template[body] but I’m getting an error body is undefined