Unable to use images with jsPDF

everyone,
I’m trying to create a pdf file with jsPDF but I need a logo at the top of the page.
I’ve tried a .jpg and a .png file bu I always get the erro that the file is not a .jpg file or a .png file.
I’ve tried everything I can remember and I cant’t make it work and it’s a pity because jsPDF is very straight forward to use.
Can anyone help?
Thank you in advance

I tried several different images and expected the image to appear in the created pdf.

How to create connect graphs for Website URL’s?

I’m currently tracking my website activity (url’s visited, google search). I want to construct a connected graph with these URL’s. What is the best approch to do that?

What I have tried:
storing web activites in the below format

{ 
  timestamp: 2024-05-25, 16:13:43, 
  parent_url: https://www.reddit.com, 
  type: visit, 
  url: https://www.reddit.com/t/animals_and_pets/
}.

I’m extracting parent URL using

console.log(document.referrer)

Sometimes the parent URL is empty and other time its incorrect. For example if I have visited site_1 -> site_2 -> site_3. It’s showing parent URL for site_3 as site_1 instead of site_2.

I’m expecting the correct way for getting parent URL’s and structuring my logs.

Upload and parse xml file with a file upload button

I have created a HTML file with a button that get the tags from a xml file placed in the same directory as the HTML file. I am wondering if there is any way to turn this button into an uploading button to upload any XML file (from the desktop, for example) and fill the divs at the same time. Here is the code:

    <input type="button" value="Get XML data" id="users" onclick="xmlOpen()">
    
    <div id="red" style="color: red"></div>
    <div id="violet" style="color:violet"></div>
    <div id="blue" style="color:blue"></div>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};

function xmlOpen() {
xhttp.open("GET", "document.xml", true);
xhttp.send();
}

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName('title')[0];
    var y = x.childNodes[0];
    document.getElementById("red").innerHTML =
    y.nodeValue; 
    
    var x = xmlDoc.getElementsByTagName('ProjectID')[0];
    var y = x.childNodes[0];
    document.getElementById("violet").innerHTML =
    y.nodeValue; 
    
    var x = xmlDoc.getElementsByTagName('VendorName')[0];
    var y = x.childNodes[0];
    document.getElementById("blue").innerHTML =
    y.nodeValue;
}
</script>

Thanks!

How to reload in the same popup with different domain [duplicate]

I have javascript popup.

My application server is localhost:8023 and opens the page on localhost:8024

it opens the window at first,

var win = window.open('http://localhost:8024/dummy?id=test1',"_blank",'status=yes,width=500,height=500');

then, I want to reload in the same popup such as

window.open('http://localhost:8024/dummy?id=test2',win,'status=yes,width=500,height=500');

However this doesn’t open.

Is there any method to do this?

Unable to build Next.js app to run on host

I have created a small test app to learn Next/React, and it runs locally using npm run dev. But I want to host it on a domain I bought and run at SmarterASP.

When I run npm build it builds and I see a .next folder appear, containing this:

enter image description here

If I look at static, I see this:

enter image description here

I was hoping to see an index.html file or some entry point to launch the app. I feel my understanding of how Next.js apps are hosted is badly flawed.

How can I host my app on a static server? I thought you could basically host these on a file server, like React.

My Preact component does not render a child component

I am new to Preact, and I can’t get it to work. I expect this code to render “TEST SUCCESSFUL”, but it only renders “TEST”

<div id="app"></div>

<script type="importmap">
  {
    "imports": {
      "preact": "https://esm.sh/[email protected]",
      "htm/preact": "https://esm.sh/[email protected]/preact?external=preact"
    }
  }
</script>

<script type="module">
  import { render } from 'preact'
  import { html } from 'htm/preact'

  function Successful() {
    return html`
        <div>SUCCESSFUL</div>
    `
  }

  function App() {
    return html`
        <div>TEST</div>

        <Successful />
    `
  }
  render(html`<${App} />`, document.getElementById('app'));
</script>

There does not seem to be any error, either. What am I doing wrong?

Rasa: Button attached to a response

I want to put a button attached to my chatbot’s response. I don’t understand because my chatbot doesn’t return the button. Do you have the solution?

button = [
  {
    "title": "Search",
    "payload": "/search",
  }
]
response = "my text"
dispatcher.utter_message(buttons=button,text=response)

Response

I have already tried to add additional buttons in the table, not to store the table in a variable and to use it directly in utter_message()

connecting javascript code to html file/getting it to appear in html

I’m currently working on a project that involves an NBA api that utilizes promises and async functions. In this case, I’m not sure why my javascript function (updatetable) is not showing up in the section when called.

Here’s this section I have in HTML:

<div class="second-row-hidden">
            <h1>Predicted Roster </h1>
            <table>
                <thead>
                    <tr class="stat-names">
                        <th id="player">Player</th>
                        <th id="player-country">Country</th>
                        <th id="player-gp">GP</th>
                        <th id="player-mp">MP</th>
                        <th id="player-ppg">PPG</th>
                        <th id="player-rpg">RPG</th>
                        <th id="player-apg">APG</th>
                        <th id="player-bpm">BPM</th>
                    </tr>
                </thead>
                <tbody id="player-data">
                    </tr>
                        <td colspan="8">Loading...</td>
                    </tr>
                </tbody>
            </table>
        </div>
<script src="script.js"></script>

Here is the Javascript file:

async function filterByConditions() {
    const finalPlayers = [];
    const playerStats = await fetchPlayerStats();

    for (let i = 0; i < playerStats.length; i++) {
        const player = playerStats[i];
        if (player.Country === 'USA' && player.GP >= 60 && player.MIN >= 30) {
            finalPlayers.push(player);
        }
    }
    return finalPlayers.slice(0,12);
}

async function updateTable() {
    const finalPlayers = await filterByConditions();
    const tableBody = document.getElementById('player-data');
    tableBody.innerHTML = '';

    finalPlayers.forEach(player => {
        const row = document.createElement('tr');
        Object.keys(player).forEach(key => {
            const cell = document.createElement('td');
            cell.textContent = player[key];
            row.appendChild(cell);
        });
        tableBody.appendChild(row);
    });
}

updateTable();

There is more async functions that build upon each other prior to filterbyConditions(). At the end with filterbyConditions() it is supposed to return an array of dictionaries with the keys listed in the html section ex: {Player: Stephen Curry, Country: USA, GP: 65…etc…} that hopefully displays each element into the table cells in html. Any help is appreciated!

I tried implementing the script straight into the html file and leaving it in an external file. Nothing changed. I’ve tried almost everything to get the html connected to the javascript and I’m not sure what the issue is.

How do I write this code without using .innerHTML?

I am writing a JavaScript code where some characters of the string have a color and I want to display them through the HTML elements. I only want the ‘abc’ to be blue and no color change with ‘def’.

For example, if there’s a variable:

word = '<span style="color: blue">abc</span>def'

I used this to display the text in the HTML element:

presentCell.innerHTML = word;

Is there a way to not use .innerHTML and do the same thing? I’m worried about security problems because I am getting user input for ‘abc’ and ‘def’.

I am making this word variable with this function:

function changeTextColorArr (textArr, colorArr){
    resultArr = [];
    for(let i = 0; i < textArr.length; i++)
    {
        color = colorArr[i] === "" ? "black" : colorArr[i];
        beginTag =   `<span style="color: ${color}">`
        endTag= '</span>';

        result = beginTag + textArr[i] + endTag;
        resultArr.push(result);
    }
    return resultArr;
}
//I get an array of an text and an array of colors correspoding to each text

let word = changeTextColorArr(["abc"], ["blue"]) + "def"; 
console.log(word)

Issue fetching token balance from connected wallet using Solana, Jupiter Aggregator, and Jupiter APIs

I’m having trouble fetching the balance of a specific token from the connected wallet when swapping tokens using Solana, Jupiter Aggregator, and Jupiter APIs. I’ve implemented a server-side API to handle the swap process, which includes fetching quotes, generating swap instructions, and transferring platform fees using Jupiter APIs. However, I’m encountering an issue where the balance from the connected wallet is not being fetched correctly.

I’m using the getTokenAccountBalance and getAssociatedTokenAddress methods from the @solana/web3.js library to fetch the balance. Here’s the relevant code snippet from my server.js file:

app.get("/fetchBalance", async (req, res) => {
  const { address, walletAddress } = req.query;
  try {
    const tokenPublicKey = new PublicKey(address);
    const walletPublicKey = new PublicKey(walletAddress);

    const balance = await connection.getTokenAccountBalance(
      await connection.getAssociatedTokenAddress(tokenPublicKey, walletPublicKey)
    );

    return res.status(200).json({
      balance: balance.value.uiAmount,
      decimals: balance.value.decimals
    });
  } catch (error) {
    console.error("Error fetching token balance:", error);
    return res.status(500).json({ error: "Error fetching token balance" });
  }
});

And here’s the relevant code snippet from my swap.js file:

const fetchTokenBalance = useCallback(async (tokenAddress) => {
  if (!publicKey) return;

  try {
    const response = await axios.get("http://localhost:3001/fetchBalance", {
      params: {
        address: tokenAddress,
        walletAddress: publicKey.toString(),
      },
    });
    const balance = response.data.balance;
    setBalances(prevBalances => ({ ...prevBalances, [tokenAddress]: balance }));
    updateTokenBalances({ ...balances, [tokenAddress]: balance });
  } catch (error) {
    console.error("Error fetching token balance:", error);
    messageApi.error("Failed to fetch token balance");
  }
}, [publicKey, updateTokenBalances, balances, messageApi]);

I’m also using Jupiter APIs to fetch prices for the tokens being swapped. Here’s the relevant code snippet from my server.js file:

app.get("/tokenPrice", async (req, res) => {
  const { addressOne, addressTwo } = req.query;
  try {
    const response = await axios.get(`https://price.jup.ag/v6/price`, {
      params: { ids: addressOne, vsToken: addressTwo },
    });
    const priceData = response.data.data[addressOne];
    if (!priceData || !priceData.price) {
      throw new Error("Invalid response from price API");
    }
    const usdPrices = {
      tokenOne: priceData.price,
      tokenTwo: 1 / priceData.price,
      ratio: priceData.price,
    };
    return res.status(200).json(usdPrices);
  } catch (error) {
    console.error("Error fetching token prices:", error);
    return res.status(500).json({ error: "Error fetching token prices" });
  }
});

I’ve added some logging statements to the fetchTokenBalance function to see if it’s being called correctly and if the correct token address and wallet address are being passed to the getTokenAccountBalance and getAssociatedTokenAddress methods. However, I’m still not able to determine the root cause of the issue.

Can anyone help me understand what might be causing the issue with fetching the balance from the connected wallet, and how I can fix it? Additionally, is fetching the balance important for swapping tokens, and if so, how does it fit into the overall swap process?

i have tried everything hlep plz

How can I grab the source of a Javascript dynamically generated image so I can create a download button on mobile browser?

I am using a script qrcode.js to generate a QR-code that I want to download so it can be ‘scanned’ on a mobile phone. The QR-code image is created after the user fills in a form and the data is used to generate the image.

I can get the download button to work on the desktop and on a mobile if the browser runs in ‘Desktop mode’. That mean that on a mobile I have to use: ‘Request Desktop Site’, that is available in Chrome on Android mobile. In regular mode in Chome on Android mobile, however, using tap and hold on the download button downloads the entire HTML file.

To figure out what was going on, I tried to alert() the source of the image after using querySelector to grab it. On the desktop browser and in ‘Desktop mode’ for in Chome on Android mobile, I am able to get the file source printed in the alert box, but in regular mode on the mobile browser, it returns an empty string. Also, although the image still appears on the mobile page, I cannot tap and hold on to it in order to initiate a download. If I use another image, as in the code below, that is not generated by Javascript, I can download it with no issue.

<img src="logo.png" alt="" class="mb-10"/>

This is how the QR-image is generated and how the download button is created:

const form = document.getElementById('generate-form');
const qr = document.getElementById('qrcode');

const onGenerateSubmit = (e) => {
    e.preventDefault();

    clearUI();

    const name = document.getElementById('name').value;
    var radios = document.getElementsByName("svc");
    let reference = service + ' ' + name;
    
    setTimeout(() => {
        // Generate the QR code with qrcode.js
        generateQRCode(reference);

        setTimeout(() => {
            // Grab the src of the QR image
            const saveUrl = qr.querySelector("img").src;
            createSaveBtn(saveUrl);
        }, 1000);
    }, 50);

}

const generateQRCode = (url) => {
    const qrcode = new QRCode('qrcode', {
        text: url,
        width: 300,
        height: 300,
    });
}

const createSaveBtn = (saveUrl) => {
    const link = document.createElement('a');
    link.id = 'save-link';
    alert(saveUrl);
    link.classList = 'bg-red-500 hover:bg-red-700  text-white font-bold py-2 rounded w-1/3 m-auto my-5';
    link.href = saveUrl;
    link.download = 'qrcode';
    link.innerHTML = 'Save Image';
    document.getElementById('generated').appendChild(link);
};

const clearUI = () => {
    qr.innerHTML = '';
    const saveBtn = document.getElementById('save-link');
    if (saveBtn) saveBtn.remove();
}

form.addEventListener('submit', onGenerateSubmit);

Below are the images of the alert box that shows the src of the QR code in the different modes on mobile:

On mobile

On mobile while in Request Desktop Site

Is there a way I can get the src of the dynamically generated image on mobile? Does a browser work differently on a mobile than on a desktop? I have noticed that on other websites, there are certain images that I can’t download with tap and hold as well.

I’m new to Javascript and HTML so any help is very much appreciated. Thank you so much in advanced.

How to Add an Onclick event with React.forwardRef to open a Modal Box

I am an electrical engineer attempting to write a portfolio with JavaScript and Typescript, apologies if my question is trivial.

The following code, created a generalised parent, which creates ‘cards’ of work experience.

The following code works correctly, but I am trying to add an onclick event to the child events. I attempt to add an ‘onclick’ attribute to open a simple modal box with some text, but I am getting errors stating I need :

React.MouseEventHandler<HTMLAnchorElement>

I am wondering if there is a way to add an ‘onclick event’ to these child events? Specifically the “works-card” class? Or how to redeclare this block with a MouseEveentHandler?

I would really appreciate any help!

import React from 'react'
import { Github, Link, works } from '../../../library'
import { Headings } from '../../core/headings/headings'
import './style.css'

const Works = React.forwardRef<HTMLDivElement>((props, ref) => {
  return (
    <div ref={ref} className="works">
      {/*  Display the section title and subtitle */}
      <Headings title="Working" subtitle="Places I've Worked" />
      <div className="projects-grid">
        {works.map((work) => (
          <a
            className="works-card"
            target="_blank"
            key={work.title}
            rel="noreferrer"
            
          >
            <p className="project-name">{work.title}</p>
            <div className="project-language">
              {work.languages.map((language) => (
                <span key={language}>{language}</span>
              ))}
            </div>
          </a>
        ))}
      </div>
    </div>
  )
})



Works.displayName = 'Works'

export { Works }





Thankyou!

I have tried to ad an “onClick” attribute, with errors.