How to add a number of selected items and total price to an email form. Shopping cart

Good morning got a problem and I am have enought of thinking how to put that together so I am asking for your help. Here is a code that I am using. I want put together these 2 codes and add a total price and selected items from cart to an send e-mail. No payments just, want to send an e-mail that will include text + total price + items selected in cart.

1.

    window.addEventListener("DOMContentLoaded", function () {

  var form = document.getElementById("my-form");
  var status = document.getElementById("status");

  function success() {
    form.reset();
    status.classList.add("success");
    status.innerHTML = "Thanks!";
  }

  function error() {
    status.classList.add("error");
    status.innerHTML = "Oops! There was a problem.";
  }

  form.addEventListener("submit", function (ev) {
    ev.preventDefault();
    var data = new FormData(form);
    ajax(form.method, form.action, data, success, error);
  });
});


function ajax(method, url, data, success, error) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader("Accept", "application/json");
  xhr.onreadystatechange = function () {
    if (xhr.readyState !== XMLHttpRequest.DONE) return;
    if (xhr.status === 200) {
      success(xhr.response, xhr.responseType);
    } else {
      error(xhr.status, xhr.response, xhr.responseType);
    }
  };
  xhr.send(data);
}
    if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}
function ready() {
    var removeCartItemButtons = document.getElementsByClassName('btn-danger')
    for (var i = 0; i < removeCartItemButtons.length; i++) {
        var button = removeCartItemButtons[i]
        button.addEventListener('click', removeCartItem)
    }
    var quantityInputs = document.getElementsByClassName('cart-quantity-input')
    for (var i = 0; i < quantityInputs.length; i++) {
        var input = quantityInputs[i]
        input.addEventListener('change', quantityChanged)
    }
    var addToCartButtons = document.getElementsByClassName('shop-item-button')
    for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i]
        button.addEventListener('click', addToCartClicked)
    }

    document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
    alert('Thank you for your purchase')
    var cartItems = document.getElementsByClassName('cart-items')[0]
    while (cartItems.hasChildNodes()) {
        cartItems.removeChild(cartItems.firstChild)
    }
    updateCartTotal()
}
function removeCartItem(event) {
    var buttonClicked = event.target
    buttonClicked.parentElement.parentElement.remove()
    updateCartTotal()
}
function quantityChanged(event) {
    var input = event.target
    if (isNaN(input.value) || input.value <= 0) {
        input.value = 1
    }
    updateCartTotal()
}

function addToCartClicked(event) {
    var button = event.target
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
    var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
    var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
    addItemToCart(title, price, imageSrc)
    updateCartTotal()
}
function addItemToCart(title, price, imageSrc) {
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == title) {
            alert('This item is already added to the cart')
            return
        }
    }
    var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
        </div>
        <span class="cart-price cart-column">${price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">Delete</button>
        </div>`
    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
    cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}

function updateCartTotal() {
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    for (var i = 0; i < cartRows.length; i++) {
        var cartRow = cartRows[i]
        var priceElement = cartRow.getElementsByClassName('cart-price')[0]
        var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
        var price = parseFloat(priceElement.innerText.replace('zl', ''))
        var quantity = quantityElement.value
        total = total + (price * quantity)
    }
    total = Math.round(total * 100) / 100
    document.getElementsByClassName('cart-total-price')[0].innerText = total + 'zl'
}

For sending an e-mail I am using formspree.io. The html site is not hosted yet and I dont really know if I can make this happen without hosting or just in JS. Please Help

Kind Regards

Make a php routine check every 30 seconds

I have this code running on the header of my site :

<?php if(($Variable1 > 0) && (isset($_SESSION["role"]) && ($_SESSION["role"]==12 || $_SESSION["role"]==13))){ ?>
            <button type="button" class="btn btn-danger btn-block btn-block"><i class="fa fa-exclamation-triangle">
            </i> Number Left: <?php echo $NumberLeft; ?></button>
            <?php } ?>

i want this code to run every 30 seconds

I cant make a page regresh every 30 seconds because i’m losing the data that is not saved till then in that page. So i need only the check of the specific banner .
I tried refreshing the header but its refreshing the whole page

In React, how can I make a single api call, set the result to a state variable, and display it?

I am programming a react application where I need to make a single async api call, save the result to a state variable and display the result. I am using an axios instance where the response of the api call is a nested object. For example:

{
    kanji:
        {character: "", stroke:""},
    quote: "string"
}

So far I have the following code where I am able to console.log the homeData object successfully. However I get the error: ‘TypeError: homeData is undefined’.

const Home = () =>{

    const [homeData, setHomeData] = useState({}) 

    const getHomeData = async()=>{
        instance.get("/data")
        .then(res =>{
            setHomeData(res.data)
        })
        .catch(error =>{
            console.log(error)
        })
    }
    
    useEffect(()=>{
        getHomeData()
    }, [])

    console.log(homeData)
    
    return(
        <>
          <p>{homeData}<p>
        </>
    )
}

This seems like a promise issue but I am not sure how to fix it. Thank you for your help in advance.

Multi-Level Occurrence Counting in Javascript

I am trying to count the occurrences of values for multiple objects in an array in Javascript. For the following example input (original data is much larger):

input= [
   {
      Name: "James",
      Department: "Engineering",
      employeeId: 26
   },
   {
      Name: "Roger",
      Department: "Design",
      employeeId: 21
   },
   {
      Name: "John",
      Department: "Engineering",
      employeeId: 32
   },
   {
      Name: "Roger",
      Department: "Engineering",
      employeeId: 42
   },
   {
      Name: "Roger",
      Department: "Engineering",
      employeeId: 36
   }

For this I am trying to get the following output:

Output = [
{Name: 'James', Department: 'Engineering', count:1},
{Name: 'Roger', Department: 'Design', count:1},
{Name: 'John', Department: 'Engineering', count:1},
{Name: 'Roger', Department: 'Engineering', count:2},
]

I am trying to use loops and if statements given that I am new to JS. I tried implementing variations to what is provided on

https://www.geeksforgeeks.org/how-to-count-number-of-occurrences-of-repeated-names-in-an-array-of-objects-in-javascript/.

While its counting correctly, I cant seem to capture all the groupings. Any help here would be really appreciated!

Thanks!

JS Canvas Drawing Grid

I’m trying to draw a simple grid like this: Grid

I want the grid to be 17×17. So I made a function to do that:

function drawGrid() {
  let grids = 17;
  let inc = cvs.width / 17;

  let ct = 0;
  for (let c = 0; c < cvs.width; c += inc) {
    for (let r = 0; r < cvs.width; r += inc) {
      if (ct % 2 === 0) {
        ctx.fillStyle = "#aad751";
      } else {
        ctx.fillStyle = "#a1d149";
      }
      ctx.fillRect(r, c, inc, inc);
      ct++;
    }
  }
}

Basically I have a loop that counts up 17 times in the row and column direction. Each time incrementing by the exact amount. I know width = height, so I just used width for everything. Each time I just alternate each box color, and draw it. Now on small sizes my code works perfectly, but once I make my display monitor large enough for some reason the grid becomes lines:
Example of wrong behavior

Any ideas why this is doing that?

Thanks!



Firebase Cloud Messaging – Cannot receive messages through PWA (Vue + Firebase 8.10.0)

I’ve run into a snag/gap in firebase’s setup with web applications(PWA) which is not so clear in the documentation. I have an existing PWA built on Vue@^2.6.10 and am trying to plug Firebase’s cloud messaging into it using [email protected]. It’s easy enough to configure my application to receive messages from firebase when the app is active within a browser tab by using the following code in my App.vue in a created hook.

// Includes for the component
import firebase from 'firebase/app'
import 'firebase/app'
import 'firebase/messaging'

// Within the created hook
firebase.initializeApp({
  apiKey: "XXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXX",
  authDomain: "xxxx.firebaseapp.com",
  projectId: "xxxx",
  storageBucket: "xxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxxx",
  appId: "x:xxxxxxxxx:web:xxxxxxxxxxx",
  measurementId: "G-xxxxxxxxxxx"
})
const firebaseMessaging = firebase.messaging()
firebaseMessaging.getToken()
.then((token) => { console.log("Messaging Token: ", token) })
.catch((err) => { console.log("Messaging error: ", err) })
firebaseMessaging.onMessage((payload) => {
  console.log("Message in app: ", payload)
})

While the PWA is active within a browser window/tab, I am able to successfully send a curl message to my application.

curl -X POST --header "Authorization: key=XXXXXXXXXXXX" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"to":"XXXXXXXXXXXXX","notification":{"title":"Hello","body":"World","icon":"image/mstile-150x150.png"}}'

enter image description here

However, if I try to then configure the PWA to receive notifications via the firebase service worker, this is when the documentation seems to be missing context. Below is the recommended service worker configuration from the firebase docs which I am using.

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: "xxxxx_xxxxxxxxxxxxxxx",
  authDomain: "xxxx.firebaseapp.com",
  projectId: "xxxx",
  storageBucket: "xxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxx",
  appId: "x:xxxx:web:xxxxxxxxxx",
  measurementId: "G-xxxxxxxxxxx"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

For a standard website without an existing service worker, it seems like this configuration should be enough, however, since I am tying into an existing PWA with an existing service worker, it seems I need to register firebase’s configuration with the existing PWA configuration on my application. From what I’ve found thus far, the proper configuration of that tie-in is the following.

if ("serviceWorker" in navigator) {
  wb = new Workbox(`${process.env.BASE_URL}service-worker.js`)
  wb.addEventListener("controlling", () => { window.location.reload() })
  wb.register()
  wb.register("./firebase-messaging-sw.js")
  .then(function(registration) {
    console.log("Registration successful, scope is:", registration.scope);
    })
    .catch(function(err) {
      console.log("Service worker registration failed, error:"  , err );
    })
} else {
  wb = null
}

From the look of it, this does successfully register Firebase’s configuration with my existing service worker.

enter image description here

However, while the registration looks successful from the onset it’s not actually tying into the service worker. When clicking away from the PWA’s active browser tab under this configuration, the service worker does not receive a notification when performing the same curl above. From everything I can tell thus far in the docs, the PWA should be receiving the notification and firing a default browser notification for the event, however, that’s not the case. No notification is received even though the notification did send through Firebase’s API successfully given the response from their API:

{"multicast_id":3069325822032476405,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"88f73357-6a0e-416d-8417-67608437f84d"}]}%

So, I am kind of at the end of the road in terms of what documentation and threads I can find on this topic thus far. It would seem like there’s not a great example of how to do this configuration correctly when tying into an existing service worker. I very much appreciate anyone with experience on this topic providing their insight on configurations you’ve made work using firebase and service worker on PWAs.

Many thanks!

Retrieve groups-only from a replace function

I am using named groups in a replacement method, and I want to only work with that groups object, as it may have a variable number of capture groups. As an example:

function reFunc(match, p1, p2, p3, p4, offset, string, groups) {
    console.log('*****', groups);
}
"Bob Jones is the mayor of Dallas.".replace(/(?<first>w+) (?<last>w+) is the (?<position>w+) of (?<city>w+)/, reFunc);
"Bob Jones is the mayor of Dallas, Texas.".replace(/(?<first>w+) (?<last>w+) is the (?<position>w+) of (?<city>w+), (?<state>w+)/, reFunc);

Is there a way to just ignore everything except the groups in the replacement function, for example something like:

function reFunc(..., groups) {
    ...
}

I’m getting output but the numbers or letters are not being printed. Coding practice problem (JavaScript). Code and output picture included [closed]

working on a practice problem. The problem asks write a method ‘combinations’ that takes in an array of unique elements and returns a 2D array representing all possible combinations of 2 elements in of the array

Here is the expected output:
combinations([“a”,”b”,”c”]) => [[“a”,”b”], [“a”,”c”], [“b”,”c”]]

combinations ([0, 1, 2, 3]) => [[0,1], [0,2], [0,3], [1,2], [1,3], [2,3]]

Here is my code and output:
confused on why its saying array[2] for every-one. What am I missing?

Possible to get ‘regex source’ from match?

I can get the source of a regex when it’s defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*

Or:

let r2 = /el*/;
console.log(r2.source);

Is there a way to extract that if the regex isn’t defined separately? For example, something along the lines of:

let m = "Hello".match(/el*/);
console.log(m.source?);

Using match with or without global flag [duplicate]

It seems like when using match without the global flag, it returns an object:

// Chrome dev tools
console.log("Hello Hello".match(/el*/));
VM499:1 ['ell', index: 1, input: 'Hello Hello', groups: undefined]

However, if I use the g flag, regardless of whether there is one or more results, instead of returning an object, it returns an array:

console.log("Hello Hello".match(/ello$/g));
VM512:1 ['ello']

console.log("Hello Hello".match(/el*/g));
VM550:1 (2) ['ell', 'ell']

Why does javascript convert a match that uses g to an array of strings? Perhaps if you’re looking for multiple matches you should only be using matchAll ?

How to post an image using python requests? [duplicate]

So I am trying to make a post request to a certain website where the request’s data has an image, I looked at their source and they do the following:

they first ask you to input the image file using an input element

<input type="file" id="iconImageFile" accept="image/*" name="iconImageFile"/>

then they make a request and send the file

var r = new FormData;
r.append("iconImageFile", $("#iconImageFile")[0].files[0]),
$.ajax({
    url: url,
    type: "POST",
    data: r,
    cache: !1,
    contentType: !1,
    processData: !1
})

My question is how would I be able to replicate such a request using python’s requests library? I already have all of the headers needed for verification, I am just confused on how I would send this image in the request.

session.post(url,data = {
    'iconImageFile' : open('icon.png', encoding="utf8", errors='ignore')
})

Any help would be appreciated 😀

Problem with Update in Every Refresh, localStorage, useState, useEffect

I am trying to prevent my app to go into useEffect hook and implement what is inside within a 5 second period regardless of the situation the page is refreshed or not.

My code still only fires up the useEffect hook only on page refresh. It does not really care whether 5 seconds passed it fires up in every page refresh and then does not do anything for an eternity unless you refresh the page again. It acts like a useEffect hook with empty dependency array.

How can I achieve useEffect hook to run every 5 seconds regardless the page is refreshed or not? Here is my snippet.

  const localVisitTime = localStorage.getItem('localVisitTime');
  const currentTime = new Date().getTime();
  const timeDifference = currentTime - localVisitTime;

  const [ visitTime, setVisitTime ] = useState(localVisitTime);

  if (localVisitTime && timeDifference <= 5000) {
    // Do nothing, wait!
  } else {
    localStorage.setItem('localVisitTime', new Date().getTime());
    setVisitTime(localVisitTime);
  }

  useEffect(() => {

    const fetchData = async () => {
      console.log('Data fetched!');
    }

    fetchData();
  }, [visitTime]);

syntax explanation for copying object array and add new property

Can someone explain to me why this is the only version I’ve tried that works for copying state with es6 and adding another field, out of the other ways tried that are listed below? :

const values = [{key: "1", val: "one"}, {key: "2", val: "two"}];

var works = values.map(v => {
    return {
       ...v,
       extra: "stuff"
   }
})

And all of these produce these errors:

//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff"); 

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"}) 

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v, 
   extra: "stuff"
  }
}) 

// unexpected token 'return'
var notWorks4 = values.map(v => 
   return {
    ...v, 
    extra: "stuff"
   }
) 
// unexpected 'return'
var notWorks5 = values.map(v => return ...v, extra: "stuff");

I thought the arrow was implicit return (see first 3 attempts).

Is that first way the only syntax that can be used? If there are any others, I’d like to know as I’m trying to practice and learn multiple options.. and I want the most terse, smallest option (one line).

How do I list all servers in a discord.js v12 bot

I’m trying to make a command so when you go ;listservers it brings a list of current servers the bot is in but my code is sending servers one at a time making it really slow is there anyway I could fix this? this is my current code

    message.channel.send(`Found ${client.guilds.cache.size} serversnServer List:`)
    client.guilds.cache.forEach(guild => {
        message.channel.send(`${guild.name} | ${guild.id}`)
    })