Chartjs chart not showing

I have a multiple charts that I want to display on this blade file but it seems that only one chart can display..I need to display 4.. I’ve checked the developer console and there are no errors pertaining to this issue where might I be going wrong? I’m trying to use chartjs3.0.1

On chartjs 2 this seems to work but when I tried using later version this issue has come up

@section('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.1/chart.js" integrity="sha512-HJ+fjW1Hyzl79N1FHXTVgXGost+3N5d1i3rr6URACJItm5CjhEVy2UWlNNmFPHgX94k1RMrGACdmGgVi0vptrw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js" charset="utf-8"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/bootstrap-select.min.js" charset="utf-8"></script>

 <!-------------- TOP 3 CROP COMMODITIES BY PRODUCTION VALUE --------------->

 <script>
    // Declaring variables for data to be used in graph as well as the url to pull from
    const url = "{{url('top3cropcomms')}}";
    const crop_sum = new Array();
    const crop_comm = new Array();
    // Create a document.ready function so the chart loads as soon as the page is opened
    $(document).ready(function(){
        // GET function for bringing the values from database into the variables listed above
      $.get(url, function(response){
        response.forEach(function(data){
            crop_comm.push(data.commodity);
            crop_sum.push(data.com_sum);
        });
        // setup 
        const data = {
        labels: crop_comm,
        datasets: [{
            label: 'Weekly Sales',
            data: crop_sum,
            backgroundColor: [
            'rgba(255, 26, 104, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(0, 0, 0, 0.2)'
            ],
            borderColor: [
            'rgba(255, 26, 104, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(0, 0, 0, 1)'
            ],
            borderWidth: 1
        }]
        };

        // config 
        const config = {
        type: 'bar',
        data,
        options: {
            indexAxis: 'y',
            scales: {
            y: {
                beginAtZero: true
            }
            }
        }
        };

        // render init block
        const top3Crop_Chart = new Chart(
        document.getElementById('top3cropcomm'),
        config
        );
      });
    });
</script>

<!-------------- TOP 3 LIVESTOCK COMMODITIES BY PRODUCTION VALUE --------------->

<script>
    const ls_comms_url = "{{url('top3lscomms')}}";
    const ls_sum = new Array();
    const ls_comm = new Array();
    $(document).ready(function(){
      $.get(ls_comms_url, function(response){
        response.forEach(function(data){
            ls_comm.push(data.commodity);
            ls_sum.push(data.com_sum);
        });
        // setup 
    const top3ls_data = {
      labels: ls_comm,
      datasets: [{
        label: 'Weekly Sales',
        data: ls_sum,
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

    // config 
    const  top3ls_config = {
      type: 'bar',
      top3ls_data,
      options: {
        indexAxis: 'y',
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

    // render init block
    const top3LS_Chart = new Chart(
      document.getElementById('top3lscomm'),
      top3ls_config
    );

            
      });
    });
</script>

<!-------------- CROP TRADE DATA --------------->

<script>
    const crop_trade_url = "{{url('croptradedata')}}";
    const crop_total_value = new Array();
    const year = new Array();
    $(document).ready(function(){
      $.get(crop_trade_url, function(response){
        response.forEach(function(data){
            crop_total_value.push(data.crop_total_value);
            year.push(data.year);
        });
        // setup 
    const croptrade_data = {
      labels: year,
      datasets: [{
        label: 'Weekly Sales',
        data: crop_total_value,
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

    // config 
    const  croptrade_config = {
      type: 'bar',
      croptrade,
      options: {
        indexAxis: 'y',
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

    // render init block
    const top3LS_Chart = new Chart(
      document.getElementById('croptrade'),
      croptrade_config
    );

            
      });
    });
</script>

@endsection

Check email exists and if yes, forward to dashboard page in NextJS

I have the below code on my dashboard page.jsx

'use client'

import { useSession } from 'next-auth/react'
import { redirect } from 'next/navigation'
import { getUserByEmail } from '@/utils/user'

export default async function DashboardPage() {
  const { data: session } = useSession()

  if (!(await getUserByEmail(session.user.email))) {
    redirect('/onboarding')
  } else {
    return <div>Welcome to Dashboard</div>
  }
}

getUserByEmail.js code is below.

export async function getUserByEmail(email) {
  try {
    if ((await getUsers()) === null) {
      console.log('No users in the database.')
      return null
    }

    await connectDB()
    const user = await User.findOne({ email })

    if (!user) {
      console.log('User not found by that email.')
      return null
    }

    console.log('User found by that email.')
    return user
  } catch (error) {
    console.log('Failed to fetch user:', error.message)
    return null
  }
}

The above code doesn’t run. I get a long error when compiling the code saying cannot find various modules. When I remove the 'use client', the error goes away. But I have to use 'use client' because of the useSession hook.

What would be the best way to do this?

Thank you.

How do I include spaces in InnerHTML when selecting values from a dropdown list in JavaScript and CSS?

How do I include the spaces into the value for InnerHTML ?

So I am selecting a value from a dropdown list, pulling an array list as a Constant in my JS file.

const AppleList = ['iPhone 6s' , 'iPhone 7', 'iPhone 7 Plus','iPhone 8' 
                  ,'iPhone X' , 'iPhone Xs' , 'iPhone Xs Max' ,'iPhone Xr','iPhone 11'
                  ,'iPhone 11 Pro','iPhone 11 Pro Max'
                  ,'iPhone 12','iPhone 12 Pro', 'iPhone 12 Pro Max'
                  ,'iPhone 13','iPhone 13 Pro', 'iPhone 13 Pro Max'
                  ,'iPhone 14','iPhone 14 Pro', 'iPhone 14 Pro Max'];

const GoogleList = ['Pixel 3a' , 'Pixel 4'];
const SamsungList = ['S22','S21'];
const ErrorList = ['Select'];
const Repair1List = ['back' , 'front'];
const Repair2List = ['Pixel 3a Screen', 'Pixel 4 Screen'];
const Repair3List = ['S22 Screen', 'S21 Screen'];
const RepairTypeList =['Glass/LCD Screen Repair', 'Housing / Back Glass ', 
                        ' Front Facing Camera', 'Rear Camera', 'Charge Port' ,'Volume Buttons']


function Brand(e)
{
    listselect.innerHTML="";

  if (Brandselect.value == "Apple")
  {
    AppleList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  } 
  else if(Brandselect.value == "Google")
  {
    GoogleList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  }
   else if(Brandselect.value == "Samsung")
  {
    SamsungList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  }
  else
  {
    ErrorList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  }
}
Brandselect.addEventListener('change', Brand);
Brand();



function Model(f)
{
    RepairSelect.innerHTML="";
    
  RepairTypeList.forEach(f => RepairSelect.innerHTML += `<option value=${f}">${f}</option>`)


}
listselect.addEventListener('change', Model);
Model();

I posted the photos of the values.
EX: “Iphone” 6″.

I need it to be all one string, but not sure how to get the innerHTML to do that.

Thanks!

webpack-dev-server displaying “Cannot GET /”

I’ve been working through “A Journey to Angular Development” by Sukesh Marla and am having issues at a section where webpack-dev-server is introduced. At this point the textbook has yet to get into Angular dev, this is a prerequisite chapter focused on Webpack.

Previously in the chapter, a basic example project was created consisting of the following files:

//lib1.js
export function getLib1Message() {
    return getMessage();
}
function getMessage() {
    return "lib1";
}
//lib2.js
import {getLib1Message} from "./lib1.js";
export function getLib2Message() {
    return getLib1Message() + " & " + getMessage();
}
function getMessage() {
    return "lib2";
}
//test.js
import {getLib2Message} from "./lib2.js";
alert(getLib2Message());
<!-- index.html -->
<html>
    <head>
        <title>
            JS Webpack Demo
        </title>
        <script src="./dist/main.js"></script>
    </head>
</html>

The scripts are named as the comments describe them. These are the only files present in the folder/directory where I am running the webpack-dev-server command mentioned later. For this example, the author does not indicate any usage of a webpack config file.


After installing webpack-dev-server…

npm install webpack-dev-server -g

…the author instructs us to run the following command to launch the server:

webpack-dev-server --entry ./test.js --output-filename ./dist/main.js

The author then demonstrates that the server should be running on localhost:8080

However, when I open a web browser and attempt to access the server via this domain, I receive a white page with the text “Cannot GET /”


The following is output in the Command prompt window when I run the command:

C:UsersjuricOneDriveDocuments_AngularWorkspaceChapter_6_Webpack5_Using_devserver>webpack-dev-server --entry ./test.js --output-filename ./dist/main.js
<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:8080/
<i> [webpack-dev-server] On Your Network (IPv4): http://192.168.84.104:8080/
<i> [webpack-dev-server] Content not from webpack is served from 'C:UsersjuricOneDriveDocuments_AngularWorkspaceChapter_6_Webpack5_Using_devserverpublic' directory
asset ./dist/main.js 122 KiB [emitted] [minimized] (name: main) 1 related asset
orphan modules 31.9 KiB [orphan] 14 modules
runtime modules 27.2 KiB 12 modules
cacheable modules 177 KiB
  modules by path ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/node_modules/ 105 KiB
    modules by path ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/node_modules/...(truncated) 5.3 KiB 4 modules
    modules by path ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/node_modules/...(truncated) 81.3 KiB 4 modules
    ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/node_modules/...(truncated) 4.16 KiB [built] [code generated]
    ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/node_modules/...(truncated) 14.5 KiB [built] [code generated]
  modules by path ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/client/ 71.8 KiB
    ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/client/index....(truncated) 42.4 KiB [built] [code generated]
    ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/clien...(truncated) 1.15 KiB [built] [code generated]
    ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/client/client...(truncated) 2.22 KiB [built] [code generated]
    ../../../../../AppData/Roaming/npm/node_modules/webpack-dev-server/client/module...(truncated) 26 KiB [built] [code generated]
  ./test.js + 2 modules 392 bytes [built] [code generated]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

webpack 5.83.1 compiled with 1 warning in 1554 ms

When I pull open the web browser Console in Google Chrome, I do notice the following messages:

Failed to load resource: the server responded with a status of 404 (Not Found)
DevTools failed to load source map: Could not load content for chrome-extension://ehkepjiconegkhpodgoaeamnpckdbblp/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT

And when I pull open the web browser Console in Microsoft Edge, I see the following messages:

POST https://api-js.mixpanel.com/track/?verbose=1&ip=1&_=1684537407444 net::ERR_BLOCKED_BY_CLIENT
GET https://api-js.mixpanel.com/decide/?verbose=1&version=3&lib=web&token=7dad82d18ad96fda165e06987365580e&distinct_id=00034001CE2601AE&ip=1&_=1684537408134 net::ERR_BLOCKED_BY_CLIENT
POST https://api-js.mixpanel.com/engage/?verbose=1&ip=1&_=1684537408026 net::ERR_BLOCKED_BY_CLIENT
GET https://api-js.mixpanel.com/decide/?verbose=1&version=1&lib=web&token=7dad82d18ad96fda165e06987365580e&ip=1&_=1684537408033 net::ERR_BLOCKED_BY_CLIENT
GET https://api-js.mixpanel.com/decide/?verbose=1&version=3&lib=web&token=7dad82d18ad96fda165e06987365580e&distinct_id=00034001CE2601AE&ip=1&_=1684537408514 net::ERR_BLOCKED_BY_CLIENT
GET https://api-js.mixpanel.com/decide/?verbose=1&version=1&lib=web&token=7dad82d18ad96fda165e06987365580e&ip=1&_=1684537408387 net::ERR_BLOCKED_BY_CLIENT

JavaScript PHP file upload throw POST method not allowed

Am currently local host, and my HTML looks like this:

<form method="POST" id="myForm">
    <input type="file" name="sample_image" id="sample_image">
    <div id="uploaded_image"></div>
    <button type="submit">Upload</button>
</form>

JavaScript:

const sample_image = document.getElementsByName("sample_image")[0];

sample_image.addEventListener('submit', e => {
    e.preventDefault()
    upload_image(sample_image.files[0])
})

const upload_image = (file) => {

    if(!['image/jpeg', 'image/png'].includes(file.type)) {
        document.getElementById("uploaded_image").innerHTML = '<div class="alert">Only .jpg are allowed</div>';
        document.getElementsByName('sample_image')[0].value = '';
        console.log("image format");
        return;
    }

    if(file.size > 2 * 1024 * 1024) {
        document.getElementById('uploaded_image').innerHTML = '<div>File must be ess than 2MB</div>';
        document.getElementsByName('sample_image')[0].value = '';
        console.log("image size");
        return;
    }
    
    const form_data = new FormData();
    form_data.append("sample_image", file);

    console.log(form_data)
    fetch("/upload.php", {
        method: "POST",
        body: form_data
    }).then(function(response){
        return response.json();
    }).then(function(responseData){
        document.getElementById("uploaded_image").innerHTML = '<p>Image uploaded successfully <img src="'+responseData.image_source+'" /></p>';

        document.getElementsByName("sample_image")[0].value = '';
    })
}

PHP:

if(!isset($_FILES['sample_image'])) {
    $extension = pathinfo($_FILES['sample_image']['name'], PATHINFO_EXTENSION);
    $new_name = time() . '.' . $extension;
    move_uploaded_file($_FILES['sample_image']['tmp_name'], 'images/' . $new_name);
    $data = [
        'image_source' => 'images/' . $new_name
    ];
    echo json_encode($data);
}

When I submit the form, I get a 405 error:

Post method not allowed

How best can I upload files using JavaScript?

Amongst many articles I ran into this and I still can’t see why the error message.

Variable is turning to undefined when I pass it in as a prop to another .js file

I have created my app file which turns an isAuthenticated variable to true on a successful login connection. I have verified that the Firebase API call is working correctly as only upon entry of a valid username and password does my program shift to the /admin page.

I want my header bar to hide the login button after a successful login but it is not working as my isAuthenticated variable turns to undefined once I pass it in instead of turning to true. I know this is happening because I am putting a console.log statement in my header file to print out the value of the isAuthenticated variable. In my Header.js file, I want to use this variable to control whether or not the login button appears.

This is my code for the App.js and Header.js files:

import './App.css';
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import Header from './Header';  
import LoginForm from './LoginForm'; 
import AdminPage from './AdminPage'; 

import { getAuth, signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth";
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";

const firebaseConfig = {
   //
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

function HomePage() {
  const navigate = useNavigate();
  const auth = getAuth();
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        setIsAuthenticated(true);
        navigate('/admin');
      } else {
        setIsAuthenticated(false);
      }
    });

    return () => unsubscribe();
  }, [auth, navigate]);

  const handleLogin = async (username, password) => {
    try {
      await signInWithEmailAndPassword(auth, username, password);
      console.log('Login successful');
      navigate('/admin'); // Navigate to the admin page on successful login
    } catch (error) {
      console.log(error.message);
    }
  };

  return (
    <div className="App">
        <Header
            isAuthenticated={isAuthenticated}
            handleLoginFormSubmit={handleLogin} // Pass handleLogin as a prop
        />
    </div>
  );
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/admin" element={<AdminPage />} />
      </Routes>
    </Router>
  );
}

export default App;
import React, { useState } from 'react';
import LoginForm from './LoginForm';

function Header({ isAuthenticated, handleLoginFormSubmit }) {
  const [showLoginForm, setShowLoginForm] = useState(false);

  const handleLoginButtonClick = () => {
    setShowLoginForm(true);
  };

  return (
    <header className="App-header">
      <h1 className="App-title">Family Wordle</h1>
      {isAuthenticated ? null : (
        <>
          {!showLoginForm ? (
            <button className="App-button" onClick={handleLoginButtonClick}>
              Admin Login
            </button>
          ) : (
            <LoginForm handleLogin={handleLoginFormSubmit} /> // Updated prop name
          )}
        </>
      )}
    </header>
  );
}

export default Header;

Esri Developer Api

Trying to get data from popup attribute table into html element as value. Where the code below brings an array into the popup as content, i want to bring just one piece of that data into an input element as text i.e from the code below fieldinfos, fieldName: “name”. Name is one of the attribute columns from the attribute table of the map, i want to use that in separate query (which i know how to do). Sorry, I’m a real novice with javascript. Any help greatly appreciated.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>
      Custom popup actions per feature attribute | Sample | ArcGIS Maps SDK for
      JavaScript 4.26
    </title>

    <style>
      body {
        padding: 0;
        margin: 0;
        height: 80%;
        width: 80%;
        overflow: hidden;
      }

      #viewDiv {
        position: absolute;
        right: 0;
        left: 0;
        top: 0;
        bottom: 0;
      }
    </style>

    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.26/esri/themes/light/main.css"
    />
    <script src="https://js.arcgis.com/4.26/"></script>

    <script>
      require(["esri/Map", "esri/views/MapView", "esri/layers/FeatureLayer"], (
        Map,
        MapView,
        FeatureLayer
      ) => {
        const map = new Map({
          basemap: "streets-navigation-vector"
        });

        const view = new MapView({
          container: "viewDiv",
          map: map,
          center: [-101.94981250000075, 41.20977753557709],
          zoom: 5
        });

        /********************
         * Add feature layer
         ********************/
        // sampling of breweries
        const featureLayer = new FeatureLayer({
          url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/OpenBeerDB/FeatureServer/0",
          popupTemplate: {
            title: "{name}",
            lastEditInfoEnabled: false,
            actions: [
              {
                id: "find-brewery",
                image:
                  "https://developers.arcgis.com/javascript/latest/sample-code/popup-custom-action/live/beer.png",
                title: "Brewery Info"
              }
            ],
            content: [
              {
                type: "fields",
                fieldInfos: [
                  {
                    fieldName: "name"
                  },
                  {
                    fieldName: "address1",
                    label: "address"
                  },
                  {
                    fieldName: "city"
                  },
                  {
                    fieldName: "state"
                  },
                  {
                    fieldName: "phone"
                  },
                  {
                    fieldName: "website"
                  }
                ]
              }
            ]
          }
        });

        map.add(featureLayer);

        view.when(() => {
          // Watch for when features are selected
          view.popup.watch("selectedFeature", (graphic) => {
            if (graphic) {
              // Set the action's visible property to true if the 'website' field value is not null, otherwise set it to false
              const graphicTemplate = graphic.getEffectivePopupTemplate();
              graphicTemplate.actions.items[0].visible = graphic.attributes
                .website
                ? true
                : false;
            }
          });

          const popup = view.popup;
          popup.viewModel.on("trigger-action", (event) => {
            if (event.action.id === "find-brewery") {
              const attributes = popup.viewModel.selectedFeature.attributes;
        document.getElementById("name") = "test";

              // Get the 'website' field attribute
              const info = attributes.website;
              // Make sure the 'website' field value is not null
              if (info) {
                // Open up a new browser using the URL value in the 'website' field
                window.open(info.trim());
              }
            }
          });
        });
      });
    </script>
  </head>

  <body>

    <div id="viewDiv" class="esri-widget" style="width:600px;height:600px;"></div>

</body>

</html>

ANGULAR – Template Method not executing onLoad

Im doing a simple app, but for some reason, the parent methods, that Im invokes in the template, are not working.

  1. Am I missing something?
  2. Seams like the template is executed before the TS is ready. Is this possible? If yes, how to prevent it?

Template:


    <app-search-list
      [dataResults]="Pokemons"
      [pokemonArray]="pokemonDataArray"
      (dataPokemonEvent)="receivePokemonData($event)"
    ></app-search-list>

    <app-search (dataEvent)="receiveCustomData($event)">
      <p style="background-color: yellow">share data: {{ msg }}</p>
    </app-search>

typescript

import {
  Component,
  Input,
  ViewChild,
} from '@angular/core';
import { SearchListComponent } from './search-list/search-list.component';
import { SearchComponent } from './search/search.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements AfterContentInit {
  @ViewChild(SearchListComponent) dataSearchList: any;
  @ViewChild(SearchComponent) dataSearch: any;
  @Input() msg: string = '{msg} not implemented';


  @Input() pokemonDataArray: Object[] = [];

  Pokemons = [  ];

  constructor() {}

  receiveCustomData(event: any) {
    this.msg = event;
    alert('receiveCustomData');
    console.log('receiveCustomData');
  }

  receivePokemonData(event: any) {
    console.log('receivePokemonData');
    alert('receivePokemonData');
    this.pokemonDataArray = event;
  }

  ngAfterContentInit(): void {
    // this.receiveCustomData('Test');
  }
}

How to add ‘open’ attribute in ‘detail’ tag dynamically in Angular14+

I have this sidenav component code below. Is made using details and summary tags.

It’s giving a bug when li tag is clicked and the description just open when the click is on the details.
So I want to make a verification when li is clicked and add ‘open’ attribute to the details tag.

But it’s not working and I don’t how how to fix this. Someone can help me? =(

When I try use setAttribute or just set open attribute manually and reading it’s returned to me these errors:

core.mjs:7643 ERROR TypeError: Cannot read properties of undefined (reading ‘attributes’)
core.mjs:7643 ERROR TypeError: e.target.children.setAttribute is not a function

side-nav.html

<div class="side-nav-content">
  <ul class="nav-list" [ngClass]="{ 'nav-list-open': sideNavStatus }">
    <a class="nav-list-item" (click)="sideNavStatus = !sideNavStatus">
      <img src="{{ changeSideNavButton() }}" alt="Menu burguer icon" />
    </a>
    <li
      class="nav-list-item"
      *ngFor="let item of list"
      (click)="onSubMenu($event)"
    >
      <details> //I tried using ng-open but not worked to
        <summary>
          <img
            src="{{ item.menu.icon }}"
            alt="{{ item.menu.name }} menu icon"
            class="item-icon"
          />
          <span class="item-title" [ngClass]="{ 'show-title': sideNavStatus }">
            <a class="item-title-text"
              >{{ item.menu.name }}
              <img
                src="../../../assets/side-menu-icons/arrow-down-svgrepo-com.svg"
                alt="Arrow down Icon"
                class="item-arrow-icon"
                [ngClass]="{ 'sub-menu-open': subMenuStatus }"
              />
            </a>
          </span>
        </summary>
        <div class="sub-menu-content">
          <ul class="sub-list">
            <li
              class="sub-list-item"
              *ngFor="let item of item.menu.subMenuList"
            >
              <img src="{{ item.icon }}" alt="{{ item.name }} menu icon" />
              <span>
                <a href=""
                  >{{ item.name }}
                  <img
                    [ngClass]="{ 'show-arrow': item.subSubMenuList }"
                    src="../../../assets/side-menu-icons/arrow-down-svgrepo-com.svg"
                    alt="Arrow down Icon"
                  />
                </a>
              </span>
            </li>
          </ul>
        </div>
      </details>
    </li>
  </ul>
</div>

side-nav.ts

export class SideMenuComponent {

  @Input() sideNavStatus: boolean = false;
  subMenuStatus: boolean = false;
  subMenuOpen!: boolean;

  list: MenuList[] = [...];

  changeSideNavButton(): string {
    if (this.sideNavStatus) {
      return '../../../assets/side-menu-icons/menu-collapsed-svgrepo-com.svg'
    }else {
      return '../../../assets/side-menu-icons/menu-expand-svgrepo-com.svg'
    }
  }

  onSubMenu(e: any) {
    console.log(e);
    e.target.children.setAttribute('open'); //this is not worked too
  }
}

Form element reference in AngularJS controller

I have a html file with 2 buttons outside the form. The idea is that when a button is clicked, the form will be shown and the form element “role_id” will be set to a passed value of 1 or 2. I cannot figure out the code to include inside the controller to set the value of role_id. Can you please help?
Index.html

<button class="btn btn-custom" ng-click="formToggle(1)" > Add Role 1</button>
<button class="btn btn-custom" ng-click="formToggle(2)"> Add Role 2</button>
<form class="form-horizontal" name="persForm" id="persForm" ng-submit="insertInfo(persInfo);" >
    <input type="hidden" name="role_id" id="role_id" class="form-control" ng-model="persInfo.role_id" value="" />
</ form>

Controller.js

var crudApp = angular.module('crudApp',[]);
crudApp.controller("DbController",['$scope','$http', function($scope,$http){
    $scope.formToggle = function(id){
        $('#persForm').slideToggle();
        //Code here to set form element ‘role_id’ to id
    }
}]);

I’ve tried getElementById and other javascript DOM methods but it doesn’t seem to work inside AngularJS.

TypeScript module resolution error: ‘Could not find a declaration file for module’. What am I missing?

I can’t add a JS libarary to my TS project. I installed a JS library.

I get the following error, when i try to run a server:

`Could not find a declaration file for module 'lyrics-finder'. '' implicitly has an 'any' type.
Try `npm i --save-dev @types/lyrics-finder` if it exists or add a new declaration (.d.ts) file containing `declare module 'lyrics-finder';``

This library does not have @types/lyrics-finder, so I need to create a new declaration, but I keep failing.

I created lyrics-finder.d.ts file:

`declare module 'lyrics-finder' {
  export default function lyricsFinder(artist: string | undefined, title: string | undefined): Promise<string | null>;
}`

I put this in types folder. Then I updated a tsconfig.json (added “typeRoots”, “baseUrl”)

*{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "module": "ESNext",
    "typeRoots": ["src/types"],
    "declaration": true,
    "baseUrl": "src",

    /* Bundler mode */
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },*

But all of this did not help and I am still getting the same error that module is not founded.
Do you have any ideas why?

Uppy You can only upload

i’m trying to upload multiple images with Shrine an Uppy, and when i drop the files on dashboard show up this error:

[Uppy] You can only upload:

Ive tried to get the fileData from Shrine and add it on form post here is the exemple:

document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('input[type=file]').forEach(fileInput => {
    if (fileInput.multiple) {
      multipleFileUpload(fileInput)
    } else {
      singleFileUpload(fileInput)
    }
  })
})


const singleFileUpload = (fileInput) => {
  const imagePreview = document.getElementById(
    fileInput.dataset.previewElement
  );
  const formGroup = fileInput.parentNode;

  formGroup.removeChild(fileInput);

  const uppy = fileUpload(fileInput);

  uppy
    .use(FileInput, {
      target: formGroup,
      locale: { strings: { chooseFiles: "Choose file" } },
    })
    .use(Informer, {
      target: formGroup,
    })
    .use(ProgressBar, {
      target: imagePreview.parentNode,
    })
    .use(ThumbnailGenerator, {
      thumbnailWidth: 600,
    });

  uppy.on("upload-success", (file, response) => {
    const fileData = uploadedFileData(file, response, fileInput);

    // set hidden field value to the uploaded file data so that it's submitted with the form as the attachment
    const hiddenInput = document.getElementById(
      fileInput.dataset.uploadResultElement
    );
    hiddenInput.value = fileData;
  });

  uppy.on("thumbnail:generated", (file, preview) => {
    imagePreview.src = preview;
  });
};

const multipleFileUpload = (fileInput) => {
  const formGroup = fileInput.parentNode;

  const uppy = fileUpload(fileInput);

 uppy.use(Uppy.Dashboard, {
    target: formGroup,
    inline: true,
    height: 300,
    replaceTargetContent: true,
  });

  uppy.on("upload-success", (file, response) => {
    const hiddenField = document.createElement("input");

    hiddenField.type = "hidden";

       hiddenField.name = 'item[photos_attributes][' + Math.random().toString(36).substr(2, 9) + '][image]';
    hiddenField.value = uploadedFileData(file, response, fileInput);

    document.querySelector("form").appendChild(hiddenField);
  });
};

const fileUpload = (fileInput) => {

         const uppy = new Uppy.Uppy({
    id: fileInput.id,
    autoProceed: true,
    restrictions: {
      allowedFileTypes: fileInput.accept.split(","),
    },
  });


    uppy.use(Uppy.XHRUpload, {
      endpoint: "/upload", // Shrine's upload endpoint
    });
 

  return uppy;
};

const uploadedFileData = (file, response, fileInput) => {
  if (fileInput.dataset.uploadServer == "s3") {
    const id = file.meta["key"].match(/^cache/(.+)/)[1]; // object key without prefix

    return JSON.stringify(fileData(file, id));
  } else if (fileInput.dataset.uploadServer == "s3_multipart") {
    const id = response.uploadURL.match(//cache/([^?]+)/)[1]; // object key without prefix

    return JSON.stringify(fileData(file, id));
  } else {
    return JSON.stringify(response.body);
  }
};

// constructs uploaded file data in the format that Shrine expects
const fileData = (file, id) => ({
  id: id,
  storage: "cache",
  metadata: {
    size: file.size,
    filename: file.name,
    mime_type: file.type,
  },
});

the HTML:

<div class="Uppy form-group">
           <!-- 
           <%= f.fields_for :photos, Photo.new do |p| %>
           <%=  p.hidden_field :image, class: 'upload-data ', value: p.object.cached_image_data %>
           <%= p.file_field :image, class: 'attachment-field', multiple: true %>
           <%= p.check_box    :_destroy unless p.object.new_record? %><%end %>
           -->
           <%=  file_field_tag "files[]", multiple: true %>
            </div>

i’m still confused on how to proceed to pass the files in the form.

Unable to Access A Property in JavaScript Object

I’m new to javascript and I’m working on a project where I need to access the prices property within a JavaScript object. This object is the product object from the stripe integration. When I log productData.prices, it shows undefined even though the productData object has the prices property. I’m not sure why this is happening. Can someone help me understand what might be causing this issue?

Here is the javascript code

export default function Subscription() {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const { currentUser } = useAuth();
  const [stripe, setStripe] = useState(null);

  useEffect(() => {
    const initializeStripe = async () => {
      const stripe = await loadStripe(
        process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY
      );
      setStripe(stripe);
    };

    initializeStripe();

    const q = query(collection(db, "products"), where("active", "==", true));
    getDocs(q).then((querySnapshot) => {
      const products = {};
      querySnapshot.forEach(async (doc) => {
        products[doc.id] = doc.data();
        const priceSnapshot = await getDocs(
          collection(db, "products", doc.id, "prices")
        );
        priceSnapshot.forEach((price) => {
          products[doc.id].prices = {
            priceId: price.id,
            priceData: price.data(),
          };
        });
      });
      setProducts(products);
    });
  }, []);

  async function loadCheckOut(priceId) {
    setLoading(true);
    const usersRef = doc(collection(db, "users"), currentUser.uid);
    const checkoutSessionRef = collection(usersRef, "checkout_sessions");

    const docRef = await addDoc(checkoutSessionRef, {
      price: priceId,
      trial_from_plan: false,
      success_url: window.location.origin,
      cancel_url: window.location.origin,
    });

    onSnapshot(docRef, (snap) => {
      const { error, sessionId } = snap.data();
      if (error) {
        alert(`An error occurred: ${error.message}`);
      }

      if (sessionId && stripe) {
        stripe.redirectToCheckout({ sessionId });
      }
    });
  }

  return (
    <>
      <Container className="mt-4 mb-4">
        <h1 className="text-center mt-4">Choose Your Plan</h1>
        <Row className="justify-content-center mt-4">
          {Object.entries(products).map(([productId, productData]) => {
            console.log(productData);
            console.log(productData.prices);

            return (
              <Col md={4} key={productId}>
                <Card>
                  <Card.Header className="text-center">
                    <h5>{productData.name}</h5>
                    <h5>$20.00 / month</h5>
                  </Card.Header>
                  <Card.Body>
                    <h6>{productData.description}</h6>
                    <Button
                      onClick={() => loadCheckOut(productData?.prices?.priceId)}
                      variant="primary"
                      block
                      disabled={loading}
                    >
                      {loading ? (
                        <>
                          <Spinner
                            animation="border"
                            size="sm"
                            className="mr-2"
                          />
                          Loading...
                        </>
                      ) : (
                        "Subscribe"
                      )}
                    </Button>
                  </Card.Body>
                </Card>
              </Col>
            );
          })}
        </Row>
      </Container>
    </>
  );
}

The console.log(productData); logs the following object

{
    "images": [],
    "description": "Access to dashboard",
    "tax_code": null,
    "active": true,
    "role": "premium",
    "name": "Premium",
    "metadata": {
        "firebaseRole": "premium"
    },
    "prices": {
        "priceId": "price_1N7SdbJHqW6OBlJ5itJgsGON",
        "priceData": {
            "billing_scheme": "per_unit",
            "interval": "month",
            "unit_amount": 2000,
            "currency": "usd",
            "product": "prod_NtF7pDBsqj5psh",
            "transform_quantity": null,
            "type": "recurring",
            "active": true,
            "metadata": {},
            "tax_behavior": "unspecified",
            "tiers": null,
            "tiers_mode": null,
            "interval_count": 1,
            "recurring": {
                "interval": "month",
                "aggregate_usage": null,
                "usage_type": "licensed",
                "interval_count": 1,
                "trial_period_days": null
            },
            "description": null,
            "trial_period_days": null
        }
    }
}

The console.log(productData.prices); logs undefined. Can someone help me understand what’s happening here and how i can resolve it? Thank you.

Website Responsiveness Issue on iPhones with Bootstrap 5

I am facing an issue with the responsiveness of a website I am working on, specifically on iPhones. The website is built using Bootstrap 5 and appears to be functioning correctly on Android phones as well as in Chrome Dev Tools. However, when I test it on iPhones, certain elements do not display properly.

To provide a visual representation of the problem, please find below a couple of screenshots illustrating the issue:

Android iPhone
On Android On IPhone

The issue seems to be related to how the website’s layout and components are rendered on iPhones. The elements do not align correctly, and the overall layout appears distorted. This behavior is not observed on Android devices or when using Chrome Dev Tools to simulate different mobile devices.

If you want to see the website by yourself this is the page: https://sbriser.com/universo/personaggi/Sbriser

I have already tried some troubleshooting steps like the following:

Ensured that I am using the viewport meta tag in the HTML <head> section:

html

Despite these attempts, the responsiveness issue persists on iPhones. I suspect there might be some CSS conflict or specific iPhone-related styling that I am overlooking.

If anyone has encountered a similar problem or has expertise in Bootstrap 5 and responsive web design, I would greatly appreciate your guidance and assistance. Are there any additional CSS rules or JavaScript tweaks that could help ensure proper responsiveness on iPhones?

Thank you in advance for your time and expertise.