loading chart data from external json file

i am working on personalizing a single linechart with already fixed data on my website, i would to load the data using ajax or jquery from an external json file but dont know how to go about it. please i need your assistance.

find below the js code:

var tfLineChart = (function () {
let draw = Chart.controllers.line.__super__.draw; //draw shadow
var screenWidth = $(window).width();
    var chartBar1 = function () {
    var options1 = {
    series: [
            {
              data: [20, 50, 7, 100, -8, 80, 7],
            },
          ],
          colors: ["#D250FF"],
          chart: {
            type: "line",
            maxWidth: 96,
            height: 26,
            sparkline: { enabled: !0 },
          },
          plotOptions: { bar: { columnWidth: "50%" } },
          xaxis: { crosshairs: { width: 1 } },
          stroke: {
            show: true,
            curve: "smooth",
            lineCap: "butt",
            colors: undefined,
            width: 1,
            dashArray: 0,
          },

          tooltip: {
            enabled: false,
            fixed: { enabled: !1 },
            x: { show: !1 },
            y: {
              title: {
                formatter: function (e) {
                  return "";
                },
              },
            },
            marker: { show: !1 },
          },
          states: {
            hover: {
              filter: {
                type: "none",
                value: 0,
              },
            },
          },
        },
        chart1 = new ApexCharts(
          document.querySelector("#line-chart-1"),
          options1
        );
      chart1.render();
    };

No overload matches this call error in React Native

Issue

The following code throws an error. The code is a minimal executable code to reproduce the error of the original one.

import React from 'react';
import { Button, StyleSheet } from 'react-native';

const MyButton = () => {
  return (
    <Button
      title="Click me"
      style={styles.button}
    />
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#0f0',
    color: '#fff',
    padding: 10,
  },
});

The error:

No overload matches this call.
  Overload 1 of 2, '(props: ButtonProps): Button', gave the following error.
    Type '{ title: string; style: { backgroundColor: string; color: string; padding: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps>'.
      Property 'style' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps>'.
  Overload 2 of 2, '(props: ButtonProps, context: any): Button', gave the following error.
    Type '{ title: string; style: { backgroundColor: string; color: string; padding: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps>'.
      Property 'style' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps>'.ts(2769)

As a result, the react native webpage is empty.

Environment

  • Windows 11
  • npm 10.8.2

What I did so far

I checked the following pages in vain.

What should I do to solve this?

How to add speech to text feature. When I say dot, it writes the dot character

I’m trying to make speech to text and I want to add a function when I say a period or the end of a sentence so that it does the given punctuation

And another thing I can’t figure out how to add a function to always write after the cursor where I click in the text?

function startDictation() {
        if (window.hasOwnProperty('webkitSpeechRecognition')) {
            

            var recognition = new webkitSpeechRecognition();
            
            recognition.continuous = true;
            recognition.interimResults = true;
           
            recognition.lang = "cs-CZ";
            let p = document.createElement('p');
            const words = document.querySelector('.words');
            
            
            recognition.addEventListener('result', e => {
                const transcript = Array.from(e.results)
                .map(result => result[0])
                .map(result => result.transcript)
                .join('');

                const poopScript = transcript.replace(/otazník|poep|poo|shit|dump/gi, '.');
                p.textContent = poopScript;
    
                

                if (e.results[0].isFinal) {
                    p = document.createElement('p');
                   
                    }
                });

Hello, I’m trying to make speech to text and I want to add a function when I say a period or the end of a sentence so that it does the given punctuation

Pinia Store caching state values

So, I am having issue with my Pinia store and router guard. Issue is following:
When i go trough ‘logout’ function that basically do following, everything comes in place.

logout function in auth.js pinia store
`async logout() {
this.user = null;
this.session = null;
this.token = null;
this.isEmailVerified = false;

  // Clear local storage
  localStorage.removeItem('user');
  localStorage.removeItem('session');
  localStorage.removeItem('token');
  localStorage.removeItem('isEmailVerified');

  const showStore = useShowStore();
  showStore.closeMenu()
 },`

But when I mannualy remove my session from chrome dev tools(remove session from local storage, token, user, and isEmailVerified) Pinia obviously does not update the state. But the issue is following: I try to get the state from pinia in router guard, and it still keeps previous state, it does not go and actually look in local storage and gets me updated data for session, token, etc

Here is my auth.js pinia store:

 `import { defineStore } from 'pinia';
 import { useShowStore } from "@/store/showStore";

 export const useAuthStore = defineStore({
 id: 'auth',
 state: () => ({
 user: JSON.parse(localStorage.getItem('user')) || null,
 session: JSON.parse(localStorage.getItem('session')) || null,
 token: localStorage.getItem('token') || null,
 isEmailVerified: JSON.parse(localStorage.getItem('isEmailVerified')) || false,
 }),
 getters: {
 isAuthenticated: () => !!localStorage.getItem('token') || null,
 },
 actions: {
 async login(email, password) {
 //...`

And here is router guard

`router.beforeEach((to, from, next) => {
 const authStore = useAuthStore();

 //here it prints session after removing manually
 console.log('Is Authenticated:', authStore.isAuthenticated);

 if (to.meta.requiresAuth && !authStore.isAuthenticated) {
 next('/SignIn'); // Redirect to SignIn if not authenticated
 } else if (to.meta.approachOnlyLoggedOut && authStore.isAuthenticated && authStore.isEmailVerified) {
 next('/'); // Redirect to dashboard if authenticated and email verified
 } else if (authStore.isAuthenticated && !authStore.isEmailVerified && to.path !== '/EmailVerification') {
 if (to.path == "/VerifyEmail") {
 next()
 } else {
  next('/EmailVerification'); // Redirect to EmailVerification if email is not verified
 }
 } else {
 next();
 }  
 });`

How can i get fresh state each time? I don’t want to update state trough action in router, since I will use this ‘isAuthenticated’ on many places in the app, so I don’t want to invoke another action before i get the state, I want this logic centralized.

I have tried many things, but it still keeps state as previous value. Can someone help? Thanks

onClick triggering page refresh and setting page params from useParams hook as ‘undefined’

enter image description hereI have an interesting problem. I have a product page and an ‘add item’ button. When the button is clicked the product id will be updated in the ‘items’ array state variable. I’m getting the product id from the url params using ‘useParams’ hook.

Now here’s the thing. I put log statements at different steps in my code and found that when I navigate FROM the home page TO the product page, the page url param i.e., product id is correctly getting stored and logged.

But when I click the ‘add item’ button, it seems to immediately re-render the page and then sets the url param from the useParams hook – which was previously holding the proper page id – as ‘undefined’, which then is subsequently updating to the ‘items’ state variable as ‘undefined’.

Here’s the code:

import { useParams, Link } from "react-router-dom";
import { useState } from 'react';


function AddToCart() {
  const [items, setItems] = useState([]);
  const { id } = useParams();
  console.log(id);

  function addItem() {
    setItems([...items, id]);
  }

  console.log(items);

    return ( 
        <div className='add-to-cart'>
          <button className='add-btn' onClick={() => addItem()}>Add Item</button>
          {/* <Link to={`cart/${items}`}><FontAwesomeIcon className='cart-btn' icon={faBasketShopping} size='3x' /></Link> */}
        </div>
    );
}

export default AddToCart;

I looked up on Google and tried the e.preventDefault() method inside the function block but that didn’t work either. How can I solve this?

Adding screen snips of console before and after clicking the button

How to show Loading when the key changes in useSWR even if the data for the key already exist in cache?

I am using useSWR hook for data fetching. I want to show Loading, whenever the key changes. I have included the filter state in the key of useSWR, so whenever the state updates, it will call the API.

For e.g., on the UI, when I click on a Completed checkbox (Please refer the link of the playground), for the first time the value of isLoading is true. Then if I uncheck and check the Completed checkbox again, the value of isLoading is false, because the data already exist in the cache for the same key.

I know that the useSWR hook is also exposing isValidating. I can’t use this because I am also polling the api every 5 seconds. So, if I use isValidating then on the UI, loading is displayed every 5 seconds.

I want to show Loading whenever the user applies any filter. Any help would be appreciated

const [filter, setFilter] = useState({
   filterText: '',
   showCompleted: false,
});

const { data, error, isLoading, mutate } = useSWR(
    ['https://jsonplaceholder.typicode.com/todos', filter],
    async ([url, filter]) => {
        const res = await fetch(`${url}?completed=${filter.showCompleted}`);
        return await res.json();
    }
);

Playgroundhttps://stackblitz.com/edit/vitejs-vite-n8hjaa?file=src%2FApp.jsx

Passing a function with an event from child to parent component

I’ve a child component with an input and I want to pass info in the event with props. What’s the best way to send the data to the parent component?

In the parent component I’ve the function and the component:

 function handleAnswer(e) {
    e.preventDefault();
    const filteredValue = e.target.value.replace(/[&/\#,+()$%:*<>{}]/g, "");
    setAnswer(filteredValue);
  }

 <FrontCard handleAnswer={handleAnswer} /> 

Child component:

const FrontCard = ({ handleAnswer}) => {
  return (
<input onChange={(e) => handleAnswer2(e)}></input>
)
}

I tried to change the component in the parent. But it didn’t work.

 <FrontCard handleAnswer={(e) => handleAnswer(e)} /> 

Design MongoDB database for online Toeic exam Web topic

I am working on an online Toeic exam web project conducted with MERN. However, I’m having trouble designing the database. The requirement will be that there will be topics, for example ETS 2024, ETS 2023,… each topic has tests such as Test 1, Test 2, … Each test has 7 Parts, each part has ways Different ways of dividing questions. For example, Part 1 will be single questions with 4 answers, Part 2 will also be single questions but will only have 3 answers, however part 3 uses the same paragraph to answer 3 questions with 4 answers for each question,… Quite complicated. Can someone help me?

I tried to list out a few personal ideas but it didn’t really work

Javascript is preventing the rest of the page to show

I was trying to use a javascript code given to me on a website, but it was showing nothing on the page, this is the code

<script type="text/javascript" src="http://www.theviralmailerscript.com/viralemailformatter/editor.js"></script>
<script language="JavaScript">show_editor();</script>

I couldn’t find a solution online, so I went to ChatGPT and asked to find the problem with this code and it fixed it, this is the fix from ChatGPT

<script type="text/javascript" src="//www.theviralmailerscript.com/viralemailformatter/editor.js"></script>
<script type="text/javascript">
    window.onload = function() {
        show_editor();
    };
</script>

The page has a message on top and then after that the script, but what happens now is that when the page loads, the top message appears and then disappears and just the javascript is visible

Look Here: https://viraltrafficmailer.com/themes/default/member-area/pages/email-formatter.html

This is the whole page code including the script

<!DOCTYPE html>
<html>
<head><meta charset="us-ascii">
    <title></title>
</head>
<body data-gr-ext-installed="" data-new-gr-c-s-check-loaded="14.1196.0">
    
            <h2 style="text-align: center;">Email and Text Ads Formatter</h2>

<h4 style="text-align: center;">Use this free tool, to Format your email for a better reading experience</h4>

<h4 style="text-align: center;">For Better results, a Maximum Line Length of 60 to 70 Characters is Recommended.</h4>

<h4 style="text-align: center;">Also, you can use this tool to Format your Text ads, with the Characters count Feature.</h4>

<p style="text-align: center;"><a href="dashboard.php">RETURN TO DASHBORD</a></p>

<p style="text-align: center;"></p>

<script type="text/javascript" src="//www.theviralmailerscript.com/viralemailformatter/editor.js"></script>
<script type="text/javascript">
    window.onload = function() {
        show_editor();
    };
</script>

<grammarly-desktop-integration data-grammarly-shadow-root="true"></grammarly-desktop-integration></body>
</html>

last night looking for solutions I tried everything and had no luck

I place the code in the <head>

I place the code in the <body>

I even place the code in the <HTML> after the body

I don’t know how to code, I’m just an enthusiast, I code simple little things with the help of the internet.

php transfer specific data from table to another table using a button

hello iam using core php for a system and i have two tables ( current_job , current_quotes )

each table has different columns but they have things in common i desire to move some data from a table to another using button i applied the code below but didn’t work

<a href="scripts/transfer.php?id=<?php echo $data['id']?>"

          name="current_quote"  class="text-success content-link" id="<?php echo $data['id']; ?>"> <i style="margin-left: 5px;" class="fa-solid fa-lg fa-circle-plus"></i> </a> </td>
          <a  class="btn btn-primary">

and here is the code for transfer.php


<?php
       include('../config/database.php');
       




       
        if(ISSET($_REQUEST['id'])){
                $id=$_REQUEST['id'];
               
                $query=mysqli_query($conn, "SELECT * FROM `current_quote` WHERE `id`='$id'") or die(mysqli_error());
                $data=mysqli_fetch_array($query);
                $quote_number=$data['quote_number'];
                $quote_weight=$data['quote_weight'];
               
               
               
                mysqli_query($conn, "INSERT INTO current_job (job_number,quote_number,quote_weight) VALUES( '1569', '$quote_number', '$quote_weight')") or die(mysqli_error());
      
               
                echo"<script>alert('Data successfully transfer')</script>";
              
        }
?>

Misaligned tiles while using CRS.simple in Leaflet

I have problem in my leaflet project with misaligned tiles after adding CRS.simple to my code Console show paths to negative Y values for tiles, which don’t exist in local folder. I would appreciate really any insight, advice or help on the matter. I use standard 256×256 tiles, tms for reverse y order.

function setupMap() {
var mapPath;
var minZoom;
var maxZoom;
var defaultZoom;
var centerX;
var centerY;
var southWest;
var northEast;

// Pobranie bieżącej ścieżki URL
const currentPath = window.location.pathname;

// Sprawdzenie ścieżki i ustawienie odpowiednich wartości
if (currentPath.includes('/white_orchard/index.html')) {
    mapPath = '/resources/maps/white_orchard/{z}/{x}/{y}';
    minZoom = 2;
    maxZoom = 5;
    defaultZoom = 3;
    centerX = -65.000; // Środek mapy na podstawie współrzędnych pixelowych
    centerY = -65.000;
    southWest = L.latLng(-85, -180); // Ustawienie granic
    northEast = L.latLng(0, 45);
} else if (currentPath.includes('/velen_novigrad/index.html')) {
    mapPath = '/resources/maps/hos_velen/{z}/{x}/{y}';
    minZoom = 1;
    maxZoom = 6;
    defaultZoom = 2;
    centerX = 126.000; // Środek mapy na podstawie współrzędnych pixelowych
    centerY = 115.000;
    southWest = L.latLng(0, 0); // Ustawienie granic
    northEast = L.latLng(265, 240);
} else {
    console.error('Nieznana ścieżka mapy');
    return;
}

// Użycie CRS.Simple
var map = L.map('mapid', {
    crs: L.CRS.Simple, // CRS.Simple dla płaskiej mapy
    zoomControl: false,
    fullscreenControl: true,
    center: [centerX, centerY],
    zoom: defaultZoom,
    attributionControl: 1,
    zoomSnap: 0.5,
    zoomDelta: 0.5
}); 

// Dodanie kontrolek zoomu
L.control.zoom({
    position: 'bottomright',
    zoomInTitle: 'Przybliż',
    zoomOutTitle: 'Oddal'
}).addTo(map);

// Okienko z koordynatami
map.on('click', function (e) {
    var coords = e.latlng;
    var lat = coords.lat.toFixed(5);
    var lng = coords.lng.toFixed(5);
    console.log('Map clicked at:', lat, lng);
    L.popup()
        .setLatLng(coords)
        .setContent("Koordynaty: " + lat + ", " + lng)
        .openOn(map);
});

// Granice mapy
var bounds = L.LatLngBounds(southWest, northEast);
map.setMaxBounds(bounds);

// Dodanie warstwy kafelków z opcją TMS
L.tileLayer(mapPath + '.jpg', {
    crs: L.CRS.Simple,
    minZoom: minZoom,
    maxZoom: maxZoom,
    //continuousWorld: true,
    tms: true, // Ustawienie odwrotnej numeracji kafelków
    noWrap: true,
    bounds: bounds
}).addTo(map);

L.tileLayer(mapPath + '.png', {
    crs: L.CRS.Simple,
    minZoom: minZoom,
    maxZoom: maxZoom,
    //continuousWorld: true,
    tms: true, // Ustawienie odwrotnej numeracji kafelków
    noWrap: true,
    bounds: bounds
}).addTo(map);

// Obsługa przycisku wyszukiwania koordynatów
document.getElementById('search-button').addEventListener('click', function () {
    const input = document.getElementById('coordinate-input').value;
    const coords = input.split(',').map(coord => parseFloat(coord.trim()));

    if (coords.length === 2 && !isNaN(coords[0]) && !isNaN(coords[1])) {
        const lat = coords[0];
        const lng = coords[1];

        // Przesunięcie mapy na nowe współrzędne
        map.setView([lat, lng], defaultZoom);

        // Wyświetlenie dymka na mapie
        L.popup()
            .setLatLng([lat, lng])
            .setContent("Koordynaty: " + lat + ", " + lng)
            .openOn(map);
    } else {
        alert("Wpisz poprawne współrzędne w formacie 'lat,lng'");
    }
});
}
// Wywołanie funkcji po załadowaniu DOM
 document.addEventListener('DOMContentLoaded', function() {
    setupMap();
 });

How can I build a portfolio that showcases my skills as a new web designer? [closed]

I’m a beginner web designer looking to build a portfolio that effectively showcases my skills and projects. I have experience in [mention any specific skills or tools you’re familiar with, like HTML, CSS, JavaScript, or design software].

I’m wondering:

What types of projects should I include to best demonstrate my abilities?
Are there any specific platforms or formats you recommend for hosting my portfolio?
How can I present my work in a way that stands out to potential clients or employers?
Any tips for writing descriptions or case studies for my projects?
Thanks in advance for your advice!”

What I Tried: “I’ve started to gather a few projects that showcase my skills in web design, including [mention any specific projects, even if they’re just practice designs]. I’ve also looked at some existing portfolios online for inspiration and tried to identify common elements that stand out.”

What I Was Expecting: “I was hoping to get advice on how to select the best projects to include, the most effective ways to present my work, and any recommended platforms for hosting my portfolio. I want to ensure that my portfolio not only displays my skills but also attracts potential clients or employers.”

Cannot move mediaelement.js player progress bar manually

Suddenly MediaElement.js player progress bar can’t be moved / dragged manually. When its a mp4 video / video player, If I try to move it, its stops playing, and position the pointer at the beginning.
If its a audio player (mp3), the progress bat is not moving at all. In addition, for audio, no total time is showing

Currently we are using MediaElement version 4.x. But I tried with version 7.x as well. not working. Its implemented with Drupal 10 and jQuery. I see its working locally but not in the live server. I don’t know, if there is any dependency on server configurations. I set preload as “auto” – still not working.

No Error log or console log. Issues can be checked here,
https://bbsradio.com/podcast/getting-know-your-bible-september-19-2024
https://bbsradio.com/podcast/signs-life-mediums-and-messages-september-19-2024

I implemented with new custom module and implemented the settings based on on MediaElement.js documentation, but still not working with the live server.

If anyone can help me out, would be great!

Load all existing .JSON files into HTML page with JavaScript using fetch()

I have

/mysite/index.html

Then I have a folder /mysite/products/ with JSON files as following:

/mysite/products/1.json
/mysite/products/2.json
/mysite/products/3.json
   ...
/mysite/products/578.json

and etc…

Every JSON file looks like this:
[{"id":1,"name":"16' Tire Japan","stock":145}]

In my HTML I have a table:

<table>
   <thead>
      <th>id</th>
      <th>name</th>
      <th>stock</th>
   </thead>
   <tbody id="products"></tbody>
</table>

Then I have a file /mysite/script.html connected with my HTML.

How can I fetch all existing .JSON files one by one from my /products folder into the table tbody (id=products) using JavaScript?

Now I have one JSON file for all products and I use fetch() like this:

fetch("products.json")
  .then(function(response) {
    return response.json();
    })
  .then(function(products){
    let placeholder = document.querySelector("#products");
    let out = "";
    for(let product of products){
        out += `<tr id='tr${product.id}'>
                <td class='id'>${product.id}</td>
                <td class='name'>${product.name}</td>
                <td class='stock'>${product.stock}</td>
            </tr>`;
    }
    placeholder.innerHTML = out;
  });