HTML How to use script type module? [duplicate]

When I use module and type the following:

<script src="script.js" type="module"></script>

I get this error in the console:

Access to script at ‘file:///file path here’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

However, if I remove type="module" there will be no error.
I want to use module – how can I do this?

It might not work since ESLint’s version is mismatched with the standard config

I ran command npx eslint --init. I came across following questions:

? Which style guide do you want to follow? … 
  Airbnb: https://github.com/airbnb/javascript
▸ Standard: https://github.com/standard/standard
  Google: https://github.com/google/eslint-config-google
  XO: https://github.com/xojs/eslint-config-xo

I selected Standard. Then it said:

✔ The style guide "standard" requires eslint@^7.12.1. You are currently using [email protected].
  Do you want to downgrade? · No / Yes

I selected No.

Then I said:

Note: it might not work since ESLint's version is mismatched with the standard config.

Should I be ideally downgrading? Or should I not be using standard style guide altogether?

Conditionally change text color in BootstrapVue table

I have a table created using bootstrap-vue.

Table looks like this;
enter image description here

The code for this table is as follows;

<template>
  <div>
    <b-table striped hover :items="items" :fields="fields"></b-table>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // Note 'isActive' is left out and will not appear in the rendered table
        fields: [
          {
            key: 'last_name',
            sortable: true
          },
          {
            key: 'first_name',
            sortable: false
          },
          {
            key: 'age',
            label: 'Person age',
            sortable: true,
          }
        ],
        items: [
          { isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          { isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
          { isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
        ]
      }
    }
  }
</script>

I would like to change the text colour of Person age column such that if age is >= 20, colour is green and red if otherwise.

I am using vue.js v2.6

How to add new ENUM value to existing table using sequalize in PostgreSQL database?

Let’s say I created some table in my PostgreSQL database using sequelize:

status: {
        type: Sequelize.ENUM(["approved", "rejected", "new"]),
        allowNull: true
},

As you can see, there are 3 ENUM values, now, I need to add one more ENUM value using new migration. I was trying to do this something like this, but it doesn’t work:

'use strict';

module.exports = {
  async up (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("ALTER TABLE risky_transactions ALTER COLUMN status ADD VALUE 'question';")
  },

  async down (queryInterface, Sequelize) {
    
  }
};

So, how can I do this? No matter how, using query or pure sequelize syntax.

Thanks!

How to get XML file content in React? [duplicate]

I am trying to read XML-files in my client app.

  const handleFiles = files => {
        console.log(files[0])

}

    <ReactFileReader multipleFiles={false} fileTypes={[".xml"]} handleFiles={handleFiles}>
                <button className='btn'>Upload</button>
            </ReactFileReader>

This is the output:

File {name: 'test.xml', lastModified: 1644272268000, lastModifiedDate: Tue Feb 08 2022 00:17:48 GMT+0200 (Eastern European Standard Time), webkitRelativePath: '', size: 58152550, …}
lastModified: 1644272268000
lastModifiedDate: Tue Feb 08 2022 00:17:48 GMT+0200 (Eastern European Standard Time)
[[Prototype]]: Object
name: "F17_LeaderSFR_HebergeBYT_AuditOMC_20220208_0005.xml"
size: 58152550
type: "text/xml"
webkitRelativePath: ""
[[Prototype]]: File

When I am trying to parse the XML file to string

 var xml = new XMLParser().parseFromString(files[0], "text/xml");  

I get the following error

Uncaught TypeError: (intermediate value)(intermediate value).replace is not a function

Elementor Color Control change value with javascript

Is there a way to change value of Elementor Color Control with javascript?

I have this code:

$this->add_control(
    'themeBgColor',
    [
        'label' => esc_html__( 'Theme main color', E_VPL_TEXTDOMAIN ),
        'type' => ElementorControls_Manager::COLOR,
        'scheme' => [
          'type' => ElementorCoreSchemesColor::get_type(),
          'value' => ElementorCoreSchemesColor::COLOR_1,
        ],
        'alpha' => false,
        'classes' => 'ap-color-field',
    ]
);

This ads custom class which I can use to find this element in elementor-controls panel, but how would I change this value in editor? This is not an input field, its a button which opens global colorpicker.

The reason I want this is because I have several skin presets for my custom widget in Elementor, they they different settings for colors and these values repeat (so each skin has 20 different colors). So I dont want to duplicate controls in _register_controls function for each skin.

how to confirm stripe payment and save to database

i am using nodeJS with mongoDB.

i am using a get request to load the checkout form and then a post request to create a paymentIntent and load the stripe checkout form. then the form is submitted using a javascript file on the checkout page which then sends the user to a success page if it was successful, where would be the best place to save the purchase to the database and update the user to add it to their purchases, if i do it on the post request, it is too early and saves it before the user has a chance to pay.

routes

router.get('/pay/:id', catchAsync (async(req, res, next) => {
    if (!req.isAuthenticated()){
        req.flash('sir', 'you must be signed in')
        return res.redirect('/account/sign-in')
    }
    try{
    const { id } = req.params
    const  user  = req.user._id
    const concert =  await Concert.findById(id).populate('artist')
    const artistId = concert.artist
    const artist = await Artist.findById(artistId)
    const foundUser = await User.findById(user)
    const user_purchases = foundUser.purchased_content.toString()
    const concert_id = concert.id
    if(!concert || concert.artist.banned === 'true' || concert.visibility === 'private') {
        // return next(new AppError('page not found'))
        req.flash('paynf', 'sorry, the concert you are looking for could not be found')
    return res.redirect('/posts')
    }
    console.log(artist.stripe_id)
    res.render('pay', { concert, foundUser})
}catch(e){
    console.log(e.name)
    req.flash('paynf', 'sorry, the concert you are looking for could not be found')
    res.redirect('/posts')
}
 }))


 router.post('/pay/:id', catchAsync (async(req, res, next) => {
    if (!req.isAuthenticated()){
        req.flash('sir', 'you must be signed in')
        return res.redirect('/account/sign-in')
    }
    try{
    const { id } = req.params;
    const  user  = req.user._id
    const concert =  await Concert.findById(id).populate('artist')
    const concert_id = concert.id
    const artistId = concert.artist
    const artist = await Artist.findById(artistId)
    const stripe_id = artist.stripe_id
    const foundUser = await User.findById(user)
    if(!concert || concert.artist.banned === 'true' || concert.visibility === 'private') {
        // return next(new AppError('page not found'))
        req.flash('paynf', 'sorry, the concert you are looking for could not be found')
    return res.redirect('/posts')
    }
    const purchase = new Purchase(req.body)
    const customer = ({
        id: foundUser.cus_id,
        name: 'john',
        email: foundUser.email

    });

    // Create a PaymentIntent with the order amount and currency
    const paymentIntent = await stripe.paymentIntents.create({
    customer: customer.id,
      amount: concert.price*100,
      description: `${concert.title} by ${concert.artName}`,
      currency: "gbp",
      receipt_email: customer.email,
      automatic_payment_methods: {
        enabled: true,
      },
      application_fee_amount: Math.round(concert.price*100*0.35),
      transfer_data: {
        destination: artist.stripe_id,
      },
    });
    res.send({
      clientSecret: paymentIntent.client_secret,
    });
}
catch(e){
    console.log(e)
    return res.send('/posts')
}}))

javascript for checkout page:

const stripe = Stripe("pk_test_51KJaaVEnftAKbusC8A9kTrtzrLKklZDHQdserQ2ZrYMHRqFRfbMk9SrGVnQlLoSjIfqmOCOEsDmcsTnO0evWY2Pr00nNd02KLv");



let elements;

initialize();
checkStatus();

document
  .querySelector("#payment-form")
  .addEventListener("submit", handleSubmit);

// Fetches a payment intent and captures the client secret
async function initialize() {
  const response = await fetch(window.location.href, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ items }),
  });
  const { clientSecret } = await response.json();

  const appearance = {
    theme: 'stripe'
  }

  elements = stripe.elements({ appearance, clientSecret });

  const paymentElement = elements.create("payment");
  paymentElement.mount("#payment-element");
}

async function handleSubmit(e) {
  e.preventDefault();
  setLoading(true);

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

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

  setLoading(false);
}

// Fetches the payment intent status after payment submission
async function checkStatus() {
  const clientSecret = new URLSearchParams(window.location.search).get(
    "payment_intent_client_secret"
  );

  if (!clientSecret) {
    return;
  }

  const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

  switch (paymentIntent.status) {
    case "succeeded":
      showMessage("Payment succeeded!");
      break;
    case "processing":
      showMessage("Your payment is processing.");
      break;
    case "requires_payment_method":
      showMessage("Your payment was not successful, please try again.");
      break;
    default:
      showMessage("Something went wrong.");
      break;
  }
}

// ------- UI helpers -------

function showMessage(messageText) {
  const messageContainer = document.querySelector("#payment-message");

  messageContainer.classList.remove("hidden");
  messageContainer.textContent = messageText;

  setTimeout(function () {
    messageContainer.classList.add("hidden");
    messageText.textContent = "";
  }, 4000);
}

// Show a spinner on payment submission
function setLoading(isLoading) {
  if (isLoading) {
    // Disable the button and show a spinner
    document.querySelector("#submit").disabled = true;
    document.querySelector("#spinner").classList.remove("hidden");
    document.querySelector("#button-text").classList.add("hidden");
  } else {
    document.querySelector("#submit").disabled = false;
    document.querySelector("#spinner").classList.add("hidden");
    document.querySelector("#button-text").classList.remove("hidden");
  }}```

Failed to load resource: the server responded with a status of 404 (Not Found) Sqlite3.js

I am trying to load an sqlite3 package to the browser using requirejs module and and it won’t load.

This is the code of the JavaScript file:

requirejs(['sqlite3'], function (sqlite3) {
// const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/main.db');
const button = document.querySelector("#btnOnclick");
const fname = document.querySelector("#fname");
button.addEventListener("click", function onclick(event) {


  db.run(`INSERT INTO langs(name) VALUES(?)`, [fname], function(err) {
    if (err) {
      return console.log(err.message);
    }
    // get the last insert id
    console.log(`A row has been inserted with rowid ${this.lastID}`);
  });
db.close();

});
});

and it gives me theis error in the browser console:

screenshot of the browser console

Note:

I am using nodeJs and html & css for this project and the code works fine in my machine but on the browser gives me this error

How can I get a and b out of the array?

I’m pretty new to programming, I was trying to built an API call that I will use in another function but I’m stuck here.
I need to get a and b separately and as value out of this:

import axios from "axios";


async function main() {
await axios 
  .get('https://api.blocknative.com/gasprices/blockprices?confidenceLevels=99', {
    headers: { Authorization: 'key'},
  })
  .then(function (response) {
      const a = response.data.blockPrices[0].estimatedPrices[0].maxFeePerGas;
      const b = response.data.blockPrices[0].estimatedPrices[0].maxPriorityFeePerGas;
      return[a,b]
      });
  };
main().catch(console.error);
  
  

How can I do it?
I already take a look at scope,block and destructuring but I really can’t figure a way out.
Thanks for your help!

Sharpspring script not loading consistently on a Gatsby page

I have this page created on Gatsby and I’m including this Script from Sharpspring in the Helmet component and it loads sometimes but not all the time.
Any ideas why this happens?

import React from "react"
import ReactDom from "react-dom"
import LayoutTemplate from "../templates/LayoutTemplate/LayoutTemplate"
import { Helmet } from "react-helmet"

const Preferences = () => {    
  return (
    <LayoutTemplate>
      <Helmet>
      <script async type="text/javascript"  src="https://koi-3QNLLDDY3O.marketingautomation.services/client/form.js?ver=2.0.1" />
    <script type="text/javascript"> 
    {`
    var ss_form = {'account': 'MzawMLEwMDayAAA', 'formID': 'M0g2SbU0NjfUtTS1NNc1MTFP1LU0s0zSNTQwMzSzMDNNMTU2AgA'}; 
    ss_form.width = '100%'; 
    ss_form.domain = 'app-3QNLLDDY3O.marketingautomation.services'; 
    ss_form.target_id = 'form1'; 
    ss_form.polling = true;
    `}
    </script> 
     </Helmet>
        <div id="form1"> </div>
    </LayoutTemplate>
  )
}

export default Preferences


lockDays in Litepicker Js

Using Litepicker (https://github.com/wakirin/litepicker/) I’m having troubles adding lockDays to my calendar.
I’m retrieving some data from my DB and this is the JSON answer:

{
    "error":0,
    "reservation_counter":1,
    "reservations":[
        {
            "start_date":"2022-02-28 00:00:00",
            "end_date":"2022-03-02 00:00:00"
        }
    ]
}

Then I format the dates fields with this JS script

const obj = JSON.parse(result);
if(parseInt(obj.error) === 0) {
    var lockedArray = [];
    if(parseInt(obj.reservation_counter) > 0){
        for (let i = 0; i < parseInt(obj.reservation_counter); i++) {
            let subArray = [obj.reservations[i].start_date.slice(0, 10), obj.reservations[i].end_date.slice(0, 10)];
            lockedArray.push(subArray);
        }
    }
}

The output of this code is, as string: [["2022-02-28", "2022-03-02"]], so is compliant with the Litepicker format.

To render the calendar, I use this script:

$('input[name="litepicker"]').daterangepicker({
    parentEl: "#calendarelement-div",
    opens: 'center',
    inlineMode: false,
    minDate: new Date(),
    autoUpdateInput: true,
    singleMode: false,
    locale: {
        format: "DD/MM/YYYY",
        separator: " - "
     },
     lockDaysFormat: 'YYYY-MM-DD',
     lockDays: lockedArray,
     disallowLockDaysInRange: true,
     highlightedDays: lockedArray
});

The calendar is fully working, but it not locks the dates. I tried with hand-coded dates, but nothing.
This is an image of the result:
Calendar screenshot

The expected resut is dates between 2022-02-28 and 2022-03-02 are locked, as JSON data.

What does cancelled status mean in network tab of dev tool?

Can someone please explain what does mean by cancelled status and how to create one?

This is the screenshot of network tab

I am using highchart library in my project. When i click download pdf multiple times, the first request is successfully sent to highchart server and file is downloaded. The subsequent clicks are getting cancelled. If i do the same in my localhost using <a href="myFile.pdf" download>Download</a> and i click multiple times, files getting download for all the clicks.

How can i do something like what highchart library has implemented? This helps to avoid spam request to the server?(i think that should be the purpose of cancelled status). Please correct me if i am wrong. I am just trying to understand this concept. Sorry for the noob question.

How to play audio when rendering a component in react js

I have a react app and in that there’s a component called AudioComponent. I want to play an audio when that component loads. My code for the AudioComponent is as follow.

import mp3 from './Hymn.mp3'
    
function AudioComponent() {

     const audio = new Audio(mp3)

     useEffect(() => {
        audio.play()
      }, [])
      
        return (
          <div className="pp">
            
      This is the Audio component

    <div >

    </div>
 
          </div>
        );
      }
      
      export default AudioComponent;

when running the app the following error shows in the console.

AudioComponent.jsx:41 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

I want to play the audio when ever the audio component is used without any user interactions. what might be the issue?

console log an object returning [object Object] javascript [closed]

Took me some time but i found a solution indirectly through here.

I was trying to store object in session and then console log it out but kept getting
[object Object]

It was so frustrating i tried this and many other ways to get past this:

console.log(JSON.stringify(myObject));

But got the same results.
Finally came across this post and basically you serialize objects to JSON when setting the storage item and then deserializing them to recover the objects.

Heres what worked for me.

$(document).ready(function(){
    const myuser = new Object();
       myuser.name = "FirstName";
       myuser.age = 29;
       myuser.state = "NJ";

   sessionStorage.setItem("myUser", JSON.stringify(myuser)); 
   let myObj = JSON.parse(sessionStorage.getItem("myUser"));
   console.log(myObj);
});

Then finally got the result i was looking for.
enter image description here