How do I submit data to a hidden form field rather than submitting it on DOM?

Okay so I’m having some trouble here. I’m new to JS so my experience with Javascript is vague. I’m trying to submit a signature to a hidden element on the form I have set up. Right now, all it’s doing is submitting it to the page itself as shown here

I want it to where it posts to the form data as a hidden element so when it sends the data, it will upload it as an image.

Below is the code I have right now:

signature.js:

const canvas = document.querySelector('canvas');
const form = document.querySelector('.signform');
const clearButton = document.querySelector('.clear-button');
const ctx = canvas.getContext('2d');
let writingMode = false;

const handlePointerDown = (event) => {
writingMode = true;  
ctx.beginPath();  
const [positionX, positionY] = getCursorPosition(event);  
ctx.moveTo(positionX, positionY);
}
const handlePointerUp = () => {  writingMode = false;}
const handlePointerMove = (event) => {  if (!writingMode) return  
const [positionX, positionY] = getCursorPosition(event);  ctx.lineTo(positionX, positionY);  ctx.stroke();}
const getCursorPosition = (event) => {  positionX = event.clientX - event.target.getBoundingClientRect().x;  positionY = event.clientY - event.target.getBoundingClientRect().y;  
return [positionX, positionY];
}
ctx.lineWidth = 2;
ctx.lineJoin = ctx.lineCap = 'round';
form.addEventListener('submit', (event) => {  event.preventDefault();
  const imageURL = canvas.toDataURL();  
  const image = document.createElement('img');  image.src = imageURL;  image.height = canvas.height;  image.width = canvas.width;  image.style.display = 'block';  form.appendChild(image);  clearPad();})

const clearPad = () => {  ctx.clearRect(0, 0, canvas.width, canvas.height);}
clearButton.addEventListener('click', (event) => {  event.preventDefault();  clearPad();})
canvas.addEventListener('pointerdown', handlePointerDown, {passive: true});
canvas.addEventListener('pointerup', handlePointerUp, {passive: true});
canvas.addEventListener('pointermove', handlePointerMove, {passive: true});

previewlease.php:

<p align='center'>Landlord Signature:</p>
   <center><canvas height="100" width="300" class="signature-pad"></canvas>    
   <p><a href="#" class="clear-button">Clear</a></p>    
   <input type="hidden" name="signature" /></center><br>
<button class='btn btn-primary'>Submit to Tenant</button>

I want to be able to let the code submit to the <input type="hidden" name="signature" /> then have it post it on the next page.

Any idea I need to do to be able to make this possible?

I tried changing this but it didn’t work:

  const imageURL = canvas.toDataURL();
  //const image = document.createElement('img');  
  //image.src = imageURL;  image.height = canvas.height;  image.width = canvas.width;  image.style.display = 'block';  
  const input = document.createElement("input");
    input.setAttribute("type", "hidden");

    input.setAttribute("name", "signature");
    input.setAttribute("value", imageURL);

document.getElementById("signform").appendChild(input); 


SyntaxError: Unexpected token ‘||=’ in ClassViewer.js

Ireceive this error and I am unsure what I need to do to resolve it. It is default in a classViewer.js so not sure if I should change the code or update something. I am not sure what ||= even means.

yarn run v1.22.19
$ tsc --noEmit && eslint . --ext .ts --fix

Oops! Something went wrong! :(

ESLint: 8.56.0

/Users/mpatel1/Documents/Repos/liberty-retail-api/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.js:123
        withMethodDecorators ||=
                             ^^^

SyntaxError: Unexpected token '||='
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (/Users/mpatel1/Documents/Repos/liberty-retail-api/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.js:20:24)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)

Code:

withMethodDecorators ||=
            methodNode.kind !== 'set' &&
                node.params.some(param => param.decorators.length);

Axios POST to Docker container returns ‘No ‘Access-Control-Allow-Origin’ header is present on the requested resource’

I’ve got an app running locally (port 8080) a headless CMS running on a local docker container (port 8055) and I’m trying to make an Axios POST request from my app to the docker container. This is what I’m trying:

  const options = {
    method: 'POST',
    url: 'http://localhost:8055/auth/login',
    headers: {
      'email': '[email protected]',
      'password': 'password'
    }
  }

  try {
    return axios.request(options)
  } catch (error) {
    console.error(error)
  }

But I’m getting this error:

Access to XMLHttpRequest at 'http://localhost:8055/auth/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

How do I solve this problem?

Why does JSXGraph board appear blank?

I’m running the sample JSXGraph code in Svelte, but nothing shows up. The div has the appropriate dimensions but is blank.

I installed JSXGraph via npm, and in order for it to run at all without errors, I made the following modifications:

  • I added type:module to the package.json.
  • I added .js to every import statement within the package.
  • I imported “canvas” and defined JXG.readCanvas in renderer/canvas.js

Below is the svelte file. When it is run, hello, followed by a 500px gap, followed by another hello is displayed.

<script>
    import JXG from 'jsxgraph';
    let board = JXG.JSXGraph.initBoard('box', {boundingbox: [-5, 5, 5, -5], axis: true});
    let p = board.create('point', [1, 2], {name: 'point'});
</script>

<main>
<p>hello</p>
<div id="box"/>
<p>hello</p>
</main>

<style> 
    #box {
        max-width: 500px;
        aspect-ratio: 1/1;
    }
</style>

The problem seems to be that JSXGraph isn’t injecting into the div, which can be seen in the generated html: <div id="box" class="s-y_bCXRrkrYfP"></div>. It’s just an empty div.

Can someone help?

vueleaflet map not rendering correctly

I am experiencing an issue that others have mentioned where when the map is first loaded, not all the tiles appear, and the map doesn’t operate correctly.
enter image description here

I am importing the JS and CSS at the top of my file:

import 'leaflet'
import 'leaflet/dist/leaflet.css'

I am also waiting until the parent component is mounted before rendering the child (map):

const isMounted = ref(false)
onMounted(() => {
  isMounted.value = true
})
<MyMap v-if="isMounted" />

The map is being loaded within a container that is styled using flexbox. Could that be the issue?

Some have mentioned that this happens when the map doesn’t have correct dimensions when it is instantiated. I am checking this with offsetHeight and this does seem to be an issue:

onMounted(() => {
  console.log(mapRef.value.$el.offsetHeight)   // logs 0
})
// from l-map @ready="init"
function init() {
  console.log(mapRef.value.$el.offsetHeight)  // also logs 0 
}

The only work around I found for this is to use

setTimeout(() => mapRef.value?.leafletObject.invalidateSize(), 250)

But this is less than desirable since it makes the screen flash around and there is a delay.
Has anyone found a fix for this that avoids using invalidateSize()?
Is the issue with the flexbox styling and is there a solution for that problem?
Thanks

Angular: How to handle WebSocket error: ErrorEvent?

I have created an angular application which uses more or less the ngx-mqtt protocoll. But upon running the application I get the following error in the NodeJS console (as seen in the screenshot).

WebSocket error: ErrorEvent {
  [Symbol(kTarget)]: _WebSocket {
    _events: [Object: null prototype] {
      open: [Function (anonymous)],
      error: [Function (anonymous)],
      close: [Function (anonymous)],
      message: [Function (anonymous)]
    },
    _eventsCount: 4,
    _maxListeners: undefined,
    _binaryType: 'nodebuffer',
    _closeCode: 1006,
    _closeFrameReceived: false,
    _closeFrameSent: false,
    _closeMessage: <Buffer >,
    _closeTimer: null,
    _extensions: {},
    _paused: false,
    _protocol: '',
    _readyState: 2,
    _receiver: null,
    _sender: null,
    _socket: null,
    _bufferedAmount: 0,
    _isServer: false,
    _redirects: 0,
    _autoPong: true,
    _url: 'ws://localhost:1884/',
    _req: null,
    __zone_symbol__openfalse: [ [ZoneTask] ],
    __zone_symbol__errorfalse: [ [ZoneTask] ],
    __zone_symbol__closefalse: [ [ZoneTask] ],
    __zone_symbol__messagefalse: [ [ZoneTask] ],
    [Symbol(kCapture)]: false
  },
  [Symbol(kType)]: 'error',
  [Symbol(kError)]: AggregateError
      at __node_internal_ (node:internal/errors:174:15)
      at internalConnectMultiple (node:net:1114:18)
      at afterConnectMultiple (node:net:1667:5) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
  },
  [Symbol(kMessage)]: ''
}

I get this error when I use (global as any).WebSocket = require('ws');.If I dont use it I get the error WebSocket is not defined.

(global as any).WebSocket = require('ws'); ==> ws.polly-fill.ts (TS File) which is imported in main.ts.

You can find the whole project under the following link: [https://github.com/sohaib-96/angular-mqtt]

Login keeps directing the user to the login page despite correct login data

I built the login route using passport, there are a few issues with the validation rules and being directed to a specific page after logging in.

Login POST:

app.post(
  '/login',
  [
    body('email').custom((value) => {
      if (!value.includes('@gmail') && !value.includes('@hotmail') && !value.includes('@icloud')) {
        throw new Error('Invalid email domain. Only Gmail, Hotmail, and iCloud domains are allowed.');
      }
      return true; // Indicates validation success
    }),
    body('password').notEmpty(),
  ],
  async (req, res, next) => {
    // Validate the request using express-validator
    const errors = validationResult(req);

    // Check if there are validation errors for email
    if (!errors.isEmpty()) {
      return res.status(400).send(errors.array()[0].msg);
    }

    // Authenticate user using passport-local strategy
    passport.authenticate('local', (err, user, info) => {
      if (err) {
        return next(err);
      }

      // Check if authentication failed
      if (!user) {
        return res.status(401).send('Incorrect email or password');
      } else if(user){
        req.redirect("/home");
      }

      // Authentication successful, check if password is correct
      bcrypt.compare(req.body.password, user.password, (bcryptErr, result) => {
        if (bcryptErr) {
          return next(bcryptErr);
        }

        

        // Password is correct, log in the user and redirect to MyAccount
        req.login(user, (loginErr) => {
          if (loginErr) {
            return next(loginErr);
          }
          return res.redirect('/views/MyAccount');
        });
      });
    })(req, res, next);
  }
);

Passport Strategy Code:

    passport.use(new Strategy( async function verify(email, password, cb){
console.log("Passport.use email:",email);
console.log("Verifying User:" +email)

    try {

      const result = await db.query("SELECT * FROM DONORS WHERE email = $1", [email]);
      if (result.rows.length > 0){
        const donor = result.rows[0];
        const storedHashedPassword = donor.password;
        bcrypt.compare(password, storedHashedPassword, (err, result) => {
          if(err){
            // console.error("Error comparing passwords");
            return cb(err);
          } else{
            if (result){
              // res.render("/views/MyAccount.ejs");
              return cb(null, donor)
            } else {
              // res.send("Incorrect password");
              return cb(null, false)
            }
          }
        });
      } else {
        // res.send("User not found")
        return cb("User not found")
      }
      
    } catch (error) {
      return cb(err)
    }


}));

Despite entering correct login data, the user is directed to a page that says
‘Incorrect email or password’
I’m not sure if the problem is with the order of the code or the logic itself

Uncaught ReferenceError: AudioWorkletProcessor is not defined in flutter web

I am trying to use audio worklets from web audio api to get mic input and displaying in a wave in a flutter app, I use the dart js package in order to call the javascript functions. The code works well, but I do get an error in console that says

Uncaught ReferenceError: AudioWorkletProcessor is not defined

However after building flutter web, and unpacking as a chrome extension I get this error again, and I believe it is stopping the app from opening.

Error in chrome

this is how I add the module

    await audioContext.audioWorklet.addModule('volume-processor.js');

and volume-processor lives in the same directory as the main thread. What am I missing?

Appreciate any tips on this.

How do I import types like how I import javascript in the browser?

This seems like a niche situation. I have a bunch of JavaScript utilities I expose to my personal project via the ES6 module specification. For example:

import ModalManager from ‘https://tritarget.org/cdn/modal-manager.js’;

And this works well in browsers which use JavaScript. However I’ve been thinking it would be nice to offer some TypeScript definitions for these utils so that I could use them in the TypeScript Playground or in personal code examples.

How do I expose the .d.ts when the import is a full URL with a .js suffix? Is this even possible?

Why is this bare minimum Angular with Lexical.dev setup not working?

I was following the https://lexical.dev/docs/getting-started/quick-start

It seem straightforward.

import { createEditor } from 'lexical';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div contenteditable="true" #editable></div>
  `,
})
export class App implements AfterViewInit {
  private editor = createEditor();

  @ViewChild('editable') editable?: ElementRef<HTMLDivElement>;

  ngAfterViewInit() {
    const el = this.editable?.nativeElement;
    if (el) {
      this.editor.setRootElement(el);
      console.log('set');
    } else console.log('nop');
  }
}

Stackblitz

And I’m getting nothing and no errors. What am I missing here?

Google appscript has suddenly stopped working?

It was working fine up until yesterday, its a script to take in one number and see how many combinations another set of numbers will add up to that one number. It is producing a blank field in column J, where it has been showing what combinations will make up the top number.

function findAndDisplayMaxCombination() {
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var targetAmount = sheet.getRange("G2").getValue();
    var values = sheet.getRange("G4:G" + sheet.getLastRow()).getValues().flat();

    // Set the time limit to 3 minutes (in seconds)
    var timeLimit = 600;
    var startTime = new Date().getTime();

    // Find the combination with the most values
    var maxCombination = findMaxCombination(targetAmount, values, startTime, timeLimit);

    // Ensure the script has permission to edit the sheet
    SpreadsheetApp.getActiveSpreadsheet().toast("Authorization check passed. Updating the sheet...", "Status", 5);

    // Clear the contents of column I
    sheet.getRange("I4:I").clearContent();

    // Write each value in the max combination to column J
    for (var i = 0; i < maxCombination.length; i++) {
      sheet.getRange("I" + (i + 4)).setValue(maxCombination[i]);
    }
  } catch (error) {
    // Log any errors
    Logger.log("Error: " + error);
    SpreadsheetApp.getActiveSpreadsheet().toast("An error occurred. Check the logs for details.", "Error", 5);
  }
}

function findMaxCombination(target, values, startTime, timeLimit) {
  var result = [];

  function search(index, currentSum, currentCombination) {
    // Check if the time limit has been exceeded
    if (new Date().getTime() - startTime > timeLimit * 1000) {
      return;
    }

    if (currentSum === target) {
      if (currentCombination.length > result.length) {
        result = currentCombination.slice(); // Update result with the longer combination
      }
      return;
    }

    if (index === values.length) {
      return;
    }

    search(index + 1, currentSum, currentCombination); // Exclude the current value
    search(index + 1, currentSum + values[index], currentCombination.concat(values[index])); // Include the current value
  }

  search(0, 0, []);
  return result;
}

Twilio Number to forward an incoming call to 2+ numbers. My current build ends the call if one of the ones is off. Will conference solve this?

I’ve pasted my code below. I’ve searched through some old posts and see that the Twilio dial feature can’t delineate between a voicemail and an answer. Essentially – I only need one of the numbers to actually answer the call, but I can’t have the call end if one of the numbers is out of service. Wondering if I should be looking at running a conference instead? Or using the REST API with machine detection? Cost is a consideration here.

“ router.post(‘/incoming-call’, async (req, res) => {
const incomingNumber = req.body.To; // The Twilio number that received the call

try {
    // Fetch forwarding number(s) from Supabase
    const { data, error } = await supabase
        .from('numbers')
        .select('forwardingnumbers')
        .eq('twilionumber', incomingNumber)
        .single();

    if (error) throw error;

   // Create a new TwiML response
    const response = new VoiceResponse();
    const dial = response.dial();

    // Assuming the array contains the numbers to be dialed simultaneously
    if (data.forwardingnumbers && data.forwardingnumbers.length) {
        data.forwardingnumbers.forEach(number => {
            dial.number(number);
        });
    } else {
        throw new Error('No for`warding numbers found');
    }

    res.type('text/xml');
    res.send(response.toString());
} catch (error) {
    console.error('Error handling incoming call:', error);
    const response = new VoiceResponse();
    response.say('An error occurred, please try again later.');
    res.type('text/xml');
    res.send(response.toString());
}

});

module.exports = router; “

I’ve tested my current code and it works if both phones are on. It ends all of the forwarding if one of the two phones is off, declines the call or out of service. I’m looking at doing something with the REST API that handles voicemail and calls all numbers before connecting but thinking conference architecture might be better? Latency is a concern here. The only answer on the boards I could find was to set it up so that one of the receivers presses ‘1’. First person to press 1 gets the call connected. But that was from 2014….

Price calculation by product quantity in shopping cart

I have a problem with my calculation by product quantity function. The checkout calculation function works perfectly. Increasing the quantity of one product and including its price also works great, but if I have more products and increases the quantity of the first product from the list, the console counts all the products below.

In the last photo below, the result of clicking + on the first product on the list.

let totalPrice = 0;

// Add to cart function
const addCartBtn = section => {
  let cartBtn = document.querySelectorAll(section);
  cartBtn.forEach(btn => {
    btn.addEventListener("click", () => {
      const price = btn.parentElement.parentElement.children[3].children[0];

      let cart = document.querySelector('.cart .items');

      let item = document.createElement("div");
      item.innerHTML = 
      `
          <div class="price-info">
              <div class="price">${price.textContent}</div>
          </div>
          <div class="quantity">
              <div class="minus">-</div>
              <div class="number">1</div>
              <div class="plus">+</div>
          </div>
      `

    // Changing item's quantity
    itemQuantitySystem(price);

    // Checkout calculation
    checkoutCalculation(price);

})
})}

// Checkout calculation function
const checkoutCalculation = priceCalc => {
  priceCalc = parseFloat(priceCalc.textContent);
  totalPrice += priceCalc;
}

// Checkout calculation by quantity
const checkoutQuantity = (priceCalc, quantity) => {
  priceCalc = parseFloat(priceCalc.textContent);
  priceCalc *= quantity;
  totalPrice += priceCalc;
}

// Quantity system
const itemQuantitySystem = (priceCalc) => {
  for (const systemElement of document.querySelectorAll(".quantity")) {
    const number = systemElement.querySelector(".number");
    const minus = systemElement.querySelector(".minus");
    const plus = systemElement.querySelector(".plus");
    
    let quantity = parseInt(number.textContent);
  
    plus.addEventListener("click", () => {
      quantity++;
      number.textContent = quantity;
      checkoutQuantity(priceCalc, quantity)
    })
  }
}

How to clear all the content from the Slate editor with slate-yjs?

I am using @slate-yjs/core with @slate-yjs/react with my Slate editor for collaborative editing.

In some of the situations, I need to clean up entire document and reload with new content. As far as I know, no such API exists such that I can simply recreate/reset the underlying Y.js document.

So, is there any way to achieve this with Slate and Y.js?

Angular Expected 2 arguments but got 3

I’m providing this function for my angular animation. It has 2 arguments but the error is saying that I’m providing 3.

startAnimation() {
  setTimeout(function() {
    const synergy16 = new bofAnimate('synergy-16', {
      type: 'oneByOne',
      duration: 900
    }, function(synergyLogo16: any) {
      logoAppearsBeforeItDraws(synergyLogo16, "synergy-16");
    });
  }, 4000);
}

Error

expected 2 arguments but got 3. function logoAppearsbeforeItDraws(arg1: any, arg2: any): any

expected 2 arguments bot got 3 (parementer) synergyLogo16: any

I am providing 2 arguments so I’m very confused on these errors, any ideas?