Add dynamic javascript to woocommerce product pages

I’m trying to add dynamic content to my WooCommerce store using the Content Cast code below. Essentially I need the code on each product page with the values in the Javascript code reflecting the product data in WooCommerce – SKU, Brand, Part number, etc.

I’ve looked in to filters, and hooks just not sure how to write it. Any help would be greatly appreciated!

function enqueue_single_product_javascript()
{
    if(is_product())
    {
             <script type='text/javascript'>
      var ccs_cc_args = ccs_cc_args || [];
      
      // Product Page
      ccs_cc_args.push(['cpn', 'sku']);
      ccs_cc_args.push(['mf', 'MANUFACTURER_NAME']);
      ccs_cc_args.push(['pn', 'MANUFACTURER_PART_NUMBER']);
      ccs_cc_args.push(['upcean', 'UPC_EAN_CODE']);
      ccs_cc_args.push(['lang', 'en']);
      ccs_cc_args.push(['market', 'US']);
      
      (function () {
         var o = ccs_cc_args; o.push(['_SKey', 'ca72adc8']); o.push(['_ZoneId', '97f1b8a61f']);
         var sc = document.createElement('script'); sc.type = 'text/javascript'; sc.async = true;
         sc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.cnetcontent.com/jsc/h.js';
         var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(sc, n);
      })();
      </script>
    }
}
add_action('wp_enqueue_scripts', 'enqueue_single_product_javascript');

No response from server using Jest

Jest throws “Exceeded timeout of 5000 ms” for a very simple test, this is the test code:

'use strict';

const request = require('supertest');
const app = require('./app.js'); // Link to your server file

test('Gets the test endpoint',  done => {
    // Sends GET Request to /test endpoint
    return request(app)
    .get('/search/')
    .expect(200)
  })

this is the server side code:

app.get('/search', function(req, res) {
  const rawdata = fs.readFileSync('questions.json');
  const questions = JSON.parse(rawdata);
  res.status(200).send(questions);
});

any help greatly appreciated

I can’t insert an image into a canvas HTML

Im trying to make an space invaders game in Html css and javascript. For that i created a canvas to be the game board so where everithing moves, the problem i found is that i cant insert an image of the ship that represents the player. This is what I tried:

the index.html

    <html>
        <head>
            <title>Space Invaders Arcade</title>
            <link rel="stylesheet" href="styles.css">
            <script src="scripts.js"></script>
        </head>
        <body>
            <h2 id = "Score">Score:<br>0000</h2>
            <canvas id="gameBoard">
            </canvas>
            
        </body>
    </html>

the css

    body{
        margin : 0;
        background-color: black;
    }
    
    @font-face {
        font-family: "Fuente";
        src: url("./Archivos/fuentes/Minecraft.ttf");
        font-weight: normal;
        font-style: normal;
    }

    #Score{
        color: white;
        font-family: "Fuente";
        font-size: 30;
        top: 2%;
        left: 2%;
        position: absolute;
        transform: translate(-2%,-2%);
    }
    
    canvas{
        width: 1400px;
        height: 800px;
        border: green 5px solid;
        margin-left: 10%;
        margin-top: 5%;
    }

and the JS

    let score = 0;
    
    var imagen = new img()
    imagen.src = "./Archivos/src/player.png";
    var canvas = document.getElementById("gameBoard");
    var ctx = canvas.getContext("2d");
    
    img.onload = function(){
        ctx.drawImage(imagen, 0, 0);
    }
    
    function drawScore() {
        elem = document.getElementById("Score");
        if(score<100)
            elem.innerHTML = `Score:<br>00${number}`;
        else{
            if(score<100)
                elem.innerHTML = `Score:<br>0${number}`;
            else{
                elem.innerHTML = `Score:<br>${number}`;
            }
        }
           

}

If anyone knows what am i doing wrong it would be very helpful thanks.

Output on Narcissistic Numbers keeps being undefined

I am trying to solve a kata from Codewars but I bumped into a wall. I’ll leave the instructions down below and my code. If anyone can guide me through the answer or simply what is wrong with my code I will kindly appreciate it.

Instructions

A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

For example, take 153 (3 digits), which is narcisstic:

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

and 1652 (4 digits), which isn’t:

1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938

My Code

function narcissistic(value) {
  let sum = 0;
  for(let i = 0; i < value.length; i++){
    sum += Math.pow(value[i], 3);
    
    if(sum == value){
      return true;
    } 
    return false;
  }
}

How to share audio as voice message via Whatsapp from web (Universal Link)?

I have some audio files (mp3) hosted in a server, and I’d like to add some web functionality to share them via WhatsApp as an audio message.

I’ve been able to share texts succesfully with the following code:

whatsapp://send?text="TEXT_TO_SHARE"

but if I put the mp3 url where the “TEXT_TO_SHARE” part, it is just linking it as plain text (the url), instead of as audio (with its Play button and so).

I’ve tried with several file formats (.mpeg, .ogg), but same failed result.

Reading this documentation, it seems that the only parameter available after the what sap://send? part is text, although I was expecting something like audio or media. I’ve seen that sharing audios is be possible with the Business API “framework”, but I’d like to do it from a simple HTML. I think that the concept is named as Universal Link (doc) but I haven’t found any way to build that universal link for audio messages.

Please, do you know if it’s possible to do it? Thanks!

Why isn’t my WebMethod being called from javascript?

I’m working in ASP.Net 4. I have the following within the body tag of my aspx:

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"/> 
  <script type="text/javascript">
      function Process() {
          var CHK = document.getElementById("<%=lstAffEmployees.ClientID%>");
          var checkbox = CHK.getElementsByTagName("input");
          var counter = 0;
          for (var i = 0; i < checkbox.length; i++) {
              if (checkbox[i].checked) {
                  counter++;
                  var Attorney = label[i].innerHTML;
                  var cutoff = Attorney.indexOf('[');
                  var cAttorney = Attorney.substring(0, cutoff - 1);
                  PageMethods.saveData(checkbox[i].value, cAttorney);
                  
              }
              
          }
          return true;
      }
</script>

In my code-behind, I have:

 [WebMethod]
    public static void saveData(string attyNo, string attyName)
    {
        //mycode
    }

In debugging, I get to the PageMethods call in the javascript, but then saveData in my code-behind is never called. I don’t understand why not. Can anyone help?

Declaring types for my custom typescript module?

I am messing around with modules in my typescript react project. Trying to get them to work. I declared my async function in my .ts file with types as so here:

//Library Imports
//Firestore SDK
import {
  getFirestore,
  collection,
  getDocs,
  setDoc,
  doc,
  addDoc,
  getDoc,
} from "firebase/firestore/lite";
//Firestore Config module
import { fireApp } from "./FirestoreConfig";

const fireData = getFirestore(fireApp);

//Get all documents from collection
const getAllDocs = async (Collection: string): Promise<any[]> => {
  let baseQuery = await getDocs(collection(fireData, Collection));
  let docs: any[] = [];
  baseQuery.forEach((doc) => docs.push(doc.data()));
  return docs;
};

export { getAllDocs };

I then import “getAllDocs” in my react app.tsx and I’m getting the error
enter image description here

So I’m trying to use a d.ts file to define the type of my function, and I can’t get it working. my d.ts file looks like this. This doesn’t fix the issue.

declare module "getAllDocs" {
  export default function getAllDocs(Collection: string): Promise<any[]>;
}

How do I properly type the function to remove the error? I don’t want to ignore the error. The d.ts file is in the exact same directory as the module I am trying to export. Any help would be greatly appreciated.

Return an array of numbers, each number tells how many items per collection

I am building an nft trading platform and this problem occured to me when Implmenting some function to send all collections with one go.

for example I have 2 bored apes and 5 crypto punks lets call each of those 2 collections for non nft people :). THose collections have id, for example bored ape #1 or crypto punk #5

I need to design an array for letting the function know which id’s belong to which collection for example.

swapMultiple(["0xA020448F7448Bcce52F31065FCd5f5D6377d6f9c","0x6e169fAc89D5F943dE1DA3bB45Fa748B9466a01b"],
  [2,3],[1000, 1001, 2000, 2002, 2003]);

The first array is the array that holds all the collections

the third array is the array that holds all the id’s

the second array is that tells you how many items per collection, so for example the first 2 ids are collection #1, so you put 2

The array with objects inside looks like this

"tokens": [
    {
        "id": "11",
        "data": {
            "name": "Azuki #11",
            "image_url": "https://lh3.googleusercontent.com/wwdP0U9rcIbPU9K-jbFBFjAlS33qAVi4-axhJo9_ucjY0Rgugy-eGbIFZGm-UrVhdkKOdhWImjyOz57x_FYcEXqwE9SaFU9YG7q2Tw",
            "description": null,
            "image_preview_url": "https://lh3.googleusercontent.com/wwdP0U9rcIbPU9K-jbFBFjAlS33qAVi4-axhJo9_ucjY0Rgugy-eGbIFZGm-UrVhdkKOdhWImjyOz57x_FYcEXqwE9SaFU9YG7q2Tw=s250"
        },
        "contract": "0xed5af388653567af2f388e6224dc7c4b3241c544"
    },
    {
        "id": "11",
        "data": {
            "name": null,
            "image_url": "https://lh3.googleusercontent.com/phV8vtTRtt_Sj_54f9mu6x6aYVVKsU8G5O3Y2Ah05Kw-U8je7qcpdsomIAbp7XD7_dAI68pfzRst8myVPzt1r8ikCtnf8zAEFKkDSCc",
            "description": null,
            "image_preview_url": "https://lh3.googleusercontent.com/phV8vtTRtt_Sj_54f9mu6x6aYVVKsU8G5O3Y2Ah05Kw-U8je7qcpdsomIAbp7XD7_dAI68pfzRst8myVPzt1r8ikCtnf8zAEFKkDSCc=s250"
        },
        "contract": "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"
    },
    {
        "id": "5",
        "data": {
            "name": "Azuki #5",
            "image_url": "https://lh3.googleusercontent.com/rff2xxIvalISQZb-6akwe-H7LWBFVPuzq8KkBPecKIGXDZIbwPGANFmUgEIqiVy-afpAuwZhAWaEIi2gxZu_yJ_6BGNjjHbtmntCItQ",
            "description": null,
            "image_preview_url": "https://lh3.googleusercontent.com/rff2xxIvalISQZb-6akwe-H7LWBFVPuzq8KkBPecKIGXDZIbwPGANFmUgEIqiVy-afpAuwZhAWaEIi2gxZu_yJ_6BGNjjHbtmntCItQ=s250"
        },
        "contract": "0xed5af388653567af2f388e6224dc7c4b3241c544"
    }
],

I need to find a way to implement that function with that array of objects inside.

Right now I only implement logic to get the ids and the collections the code looks like this

  const nftAddresses = trade.victim_tokens.map((token) => {
    return token.contract;
  });
  const tokenIds = trade.victim_tokens.map((token) => {
    return token.id;
  });

Post call not placing headers in call. Axios

I’m trying to do an Api Call, this is the code I’m using

axios.get("url", userData, {
        headers: {
            Authorization: "test"
        }
    }).then((response) => console.log(response, 'users/me'))
    .catch(err => console.log(err))

Its showing me the same error everytime

401 (Unauthorized)

And on the network on chrome dev tools, the Authorization is not appearing at all

Thanks a lot.

How to make a .io game [closed]

I need help creating a game with the top-down cartoon style of a .io game, I know that .io is the domain it is commonly used for these types of addicting games. I would like some help with the JavaScript, I can most likely handle the HTML and CSS (as I know most of it.) I would like to learn JavaScript if someone could tell me a good up-to-date website that teaches for free. I need someone to help me with making the core JS that is needed and, as I understand you need node.JS and Socket.io am I correct, and will you help me?

Vuejs – call computed function from javascript defined in another computed function

I have this computed function defined in a standalone Vue component

watchForCustomer() {
  this.customerId = window.meta.page.customerId
  if(this.customerId) {
    $(document).on("click", function(element) {
      let checkout = ['checkout'].includes(element.currentTarget.activeElement.name)
      if(checkout) {
        let checkoutForm = ['checkout', 'cart'].includes(element.currentTarget.activeElement.form.action.split('/').at(-1))
        if(checkoutForm) {
          getCustomerCredit()
        }
      }
    })
  }
},

The problem is that getCustomerCredit() is not getting called.

I’ve tried to define it as:
this.getCustomerCredit
getCustomerCredit()
app.$options.getCustomerCredit()

and I get either that the function is not defined or it simply doesn’t call it.

So how can I call this getcustomerCredit inside the document on click event?

Reduce nested array of objects to array of objects

I have an array like

Const array=[
{
id:1,
name:"abc",
Address:[
   {
    City: "something",
    Country: "first country"
   },
   {
    City: "other city",
    Country: "country"
    }
  ]
},
{
...........
}
];

I have to display this nested array objects as flat key value list. So How to reduce this like below.

Reducedarray = [
  { Id: 1, name: "abc" },
  { City: "something", country: "first country"},
  { City: "other city", country: "country"},
  { Id: 2, name: "bbc" },
  { City: "bbcsomething", country: "fbbct country"},
  { City: "other city", country: "country"}
]

Using reducearray i will map with object keys and display as key value list in html.

Can anyone help me on this plz..