fetch a json array into a table [duplicate]

Team I am trying to fetch a URL which returns a array within a json, so I can make a table..

I think the array is breaking the code, anyone has any tips?

enter image description here

getData.onclick = () => {
    fetch('https://xxx.xxx.com/trackingsensor', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        }, 
    mode:"cors"
    }
)
    .then(res => res.text())
    .then((out) => {
      let jsonData = JSON.parse(out);
      console.log(jsonData);
      for (let i = 0; i < jsonData.Items[0].length; i++) {
        let earnings = jsonData.Items[0][i];
        console.log(earnings);
        myData.innerHTML +=
          "<tr><td>" + earnings.TempMax + "</td>" +
          "<td align='right'>" + earnings.TempControl + "</td>" +
          "<td align='right'>" + earnings.ProductID + "</td>" +
          "<td align='right'>" + earnings.Description + "</td></tr>";
      };
    })
    .catch(err => console.error(err));
}
<button type="button" id="getData">Get data</button>
<table>
  <thead>
    <tr>
      <th>TempMax</th>
      <th>TempControl</th>
      <th>ProductID</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody id="myData">
    <tbody>
</table>

adding a for with array but no luck.

Cannot read properties of undefined (reading ‘concat’) Vitest on initialized array

Class

class Work {
    teams = [];
    
    constructor(teams) {
        this.teams = teams
        this.teamAdded = this.teamAdded.bind(this)
    }

    teamAdded(team) {
        this.teams.concat(team)
        return this.teams
    }

    
}

Test

test('team is added on submission', async => {
  var work = new Work()
  var team = ['default team']
  expect(work.teamAdded(team).toHaveLength(1)
})

For the sake of the error that I’m dealing with the class and test shown above contain all the info needed for my explanation. While writing tests to check the length of an array after data has been pushed to it, we ran into the following error

enter image description here

I understand that the property must be initialized with an empty array before attempting to perform array methods, but I do that above and still get the same error. I also make sure the function itself is properly bound to the class as well. Reading through the documentation, I know I don’t have to spy on the function for checking the array length in vitest and attempting to mock array methods has led to brow furrowing results. Has anyone else run into this issue? Ive seen SO posts that have dealt with something similar in Jest, but I didn’t see my specific situation of already initializing the property properly aleady when i searched around. All I would like to do is test that adding a team properly concatenates with the array and returns the length I expect.

Fetching JSON data from Apps Script and displaying it on an HTML page. Error “TypeError: data.forEach is not a function” [duplicate]

I’m trying to display JSON data from an API link but I’m getting a console error:

TypeError: data.forEach is not a function
at (index):29:14

<!DOCTYPE html>
<html>
<head>
  <title>JSON API to HTML Table</title>
</head>
<body>
  <table id="data-table">
    <thead>
      <tr>
        <th>User</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Notes</th>
      </tr>
    </thead>
    <tbody id="data-body">
    </tbody>
  </table>

  <script>
    // Fetch data from the API
    fetch('https://script.google.com/macros/s/AKfycbzgutFEciOCaMboaMsXyl8M9ae5Pw3J_q9oWwTUrxeamN5t6yJWLA6IUnQhGIRu_8c3/exec')
      .then(response => response.json())
      .then(data => {
        const tableBody = document.getElementById('data-body');

        // Iterate over the data and create table rows
        data.forEach(item => {
          const row = document.createElement('tr');
          const idCell = document.createElement('td');
          UserCell.textContent = item.User;
          const nameCell = document.createElement('td');
          NameCell.textContent = item.Name;
          const EmailCell = document.createElement('td');
          EmailCell.textContent = item.Email;
          const PhoneCell = document.createElement('td');
          PhoneCell.textContent = item.Phone;
          const NotesCell = document.createElement('td');
          NotesCell.textContent = item.Notes;

          row.appendChild(UserCell);
          row.appendChild(NameCell);
          row.appendChild(EmailCell);
          row.appendChild(PhoneCell);
          row.appendChild(NotesCell);
          tableBody.appendChild(row);
        });
      })
      .catch(error => console.log(error));
  </script>
</body>
</html>

The output just shows the table title from the HTML and not the fetched JSON data.

Why can’t I run a controller through AJAX code? [closed]

I have the following form in a modal:

<div class="modal fade" id="absenceModal" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-md" role="document">

    <form role="form" method="post" id="formAbsence">
      <div class="modal-content">

        <div class="modal-header">
          <h4 class="modal-title"><b>Absence</b></h4>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        </div>

        <div class="modal-body">
          <div class="form-row">
            <div class="col-md-5 mb-3">
              <input class="form-control" type="text" name="date" id="date" readonly>
              <input class="form-control" type="number" name="no_empleado" id="no_empleado" readonly>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary back-to-first-modal">BACK</button>
          <button type="submit" class="btn btn-primary">POST</button>
        </div>

      </div>
      
    </form>
  </div>
</div>

I have this JavaScript code:

$('#formAbsence').submit(function(event) 
{
  event.preventDefault();
  
  //var formData = $(this).serialize();


  var date = $('#date').val(); 
  var no_empleado = $('#no_empleado').val(); 
  
  $.ajax(
  {
    type: 'POST',
    url: 'controller/absence.controller.php',
    data: 
    {
      action: 'create',
      date: date, 
      no_empleado: no_empleado
    },
    success: function(response) 
    {
      alert(response);
      $('#absenceModal').modal('hide');
    }
  });
});

And this is my file “absence.controller.php”:

<?php

class AbsenceController
{

    static public function data()
    {
        $resp = array();

        if ($_SERVER["REQUEST_METHOD"] == "POST") 
        {
            if (isset($_POST["action"]) && $_POST["action"] == "create") 
            {
                $resp = self::ctrCreate();
            }
            else 
            {
                $resp["error"] = "Nope.";
            }
        }
        else
        {
            $resp["error"] = "Not valid.";
        }

        echo json_encode($resp);
    }

    static public function ctrCreate()
    {
        $resp = array();

        if (isset($_POST["date"]) && isset($_POST["no_empleado"])) 
        {
            $date = $_POST["date"];
            $no_empleado = $_POST["no_empleado"];
            $reg = date("Y-m-d H:i:s");
            $num = 1;

            $conn = new mysqli("localhost", "bd", "1234", "bd_abscence");

            $sql = "INSERT INTO abscence (date, no_empleado, reg, capt) VALUES ('$date', '$no_empleado','$reg', '$num')";
            } 
            else 
            {
                $resp["error"] = "Error." . $conn->error;
            }

            $conn->close();
        }

        echo json_encode($resp);
    }
}

AbsenceController::data();

?>

This way everything works correctly. The insertion into the database is executed without problem. The problem comes when I want to give the code a more oriented approach to the MVC pattern. My file “absence.controller.php” would look like this:

<?php

require_once 'model/absence.model.php';

class AbsenceController
{
    static public function data()
    {
        $resp = array();

        if ($_SERVER["REQUEST_METHOD"] == "POST") 
        {
            if (isset($_POST["action"]) && $_POST["action"] == "create") 
            {
                $date = $_POST["date"];
                $no_empleado = $_POST["no_empleado"];
                $resp = AbsenceModel::createAbsence($date, $no_empleado);
            }
            else 
            {
                $resp["error"] = "Nope.";
            }
        }
        else
        {
            $resp["error"] = "Not valid.";
        }

        echo json_encode($resp);
    }
}

AbsenceController::data();

?>

And my file “absence.model.php” would look like this:

<?php

class AbsenceModel
{
    public static function createAbsence($date, $no_empleado)
    {
        $resp = array();

        $reg = date("Y-m-d H:i:s");
        $num = 1;

        $conn = new mysqli("localhost", "bd", "1234", "bd_abscence");

        $sql = "INSERT INTO absence (date, no_empleado, reg, capt) VALUES ('$date', '$no_empleado','$reg', '$num')";


        // Cerrar la conexión a la base de datos
        $conexion->close();
        
        return $respuesta;
    }
}

?>

When trying with the MVC approach, it doesn’t work. What am I doing wrong?

Equipment Log Google Sheets – fixing while/for loop in Google Apps Script for check in/check out based on checkbox

I am trying to create a script on google sheets where when I click a checkbox, another sheet is updated with a new row with a log of that click. My issue right now:

I’m trying to get it so that when I uncheck the checkbox, it logs when it was unchecked. My issue is, I can’t find a workaround from a while loop or a conditional loop where after it’s set to false it does the action once and does not continually do so. Here is my code:

function hours12(today=(new Date())) { 
  let hours = (today.getHours() + 24) % 12 || 12;
  return hours;
}

function TIMESTAMP() {
  let today = new Date();
  let mins = ('0'+ today.getMinutes()).slice(-2);
  let seconds = ('0'+ today.getSeconds()).slice(-2);
  let hours = hours12(today)
  let date = (today.getMonth()+1)+'-'+today.getDate()+'-'+ (today.getYear()-100);
  let time = hours + ":" + mins + ":" + seconds;
  let dateTime = date+' '+time;
  return dateTime;
}  
function onEdit() {
  let ss = SpreadsheetApp.getActive();
  let sheet = ss.getSheetByName('check-out');
  let logSheet = ss.getSheetByName("equip-log");
  let selectedRow = sheet.getActiveRange().getRow();
  let checkbox = sheet.getRange(selectedRow, 5).getValue();
  let person = sheet.getRange(selectedRow, 2).getValue();
  let equip = sheet.getRange(selectedRow, 1).getValue();
  let condition = sheet.getRange(selectedRow, 4).getValue();
  let checkout = sheet.getRange(selectedRow, 3).getValue();
  
  while (checkbox == true) {
    if (person == '' || equip == '' || condition == '' || checkout == '') {
      Logger.log('Incomplete row information while true');
      break;
    } else {
      addValues(checkbox, logSheet, equip, person, condition, checkout);
      break;
    }
  }
  if (checkbox == false) {
    let logRange = logSheet.getDataRange().getValues();
    for (i=0; i<logRange.length;i++) {
      let rangeValue = logRange[i];
      console.log(selectedRow)
      if (!rangeValue.includes(equip, person, condition)) {
        Logger.log('Incomplete row information while false');
      } else {
        addValues(checkbox, logSheet, equip, person, condition, checkout);
        sheet.getRange(selectedRow, 2).clearContent();
        sheet.getRange(selectedRow, 4).clearContent();
      }
    }
  }
}

function addValues(checkbox, logSheet, equip, person, condition, checkout) {
  const current = TIMESTAMP()
  if (checkbox == true) {
    logSheet.appendRow([equip, person, checkout, '', condition])
  } else {
    logSheet.appendRow([equip, person, '', current,  condition])
  }
} 

React Router: Unable to Navigate to a Route Using useNavigate Hook

I am currently working on a React application that uses React Router for navigation. I have a component called `ShowNotes` where I want to implement a “Delete” button that navigates to the “/DeleteNotes” route when clicked. However, I’m encountering an issue where the navigation is not working as expected.

**Here are the details of the problem:**

– I’ve confirmed that my routing setup is correct, with routes defined for both “/ShowNotes” and “/DeleteNotes”.

– I’m using the `useNavigate` hook from `react-router-dom` to handle navigation.

– When I click the “Delete” button in the `ShowNotes` component, nothing happens; the expected navigation does not occur.

**I’ve tried the following troubleshooting steps:**

1. Ensured the routing configuration is accurate.

2. Verified that the `useNavigate` hook is functioning as expected.

3. Checked the browser console for any errors (none were found).

4. Confirmed that the “DeleteNotes” component and route are correctly set up.

5. Checked for conflicting event handlers or CSS issues that might interfere with the button click.

**Despite these efforts, I still can’t get the navigation to work as intended. Can someone please provide guidance on how to resolve this issue? Any insights or suggestions would be greatly appreciated.**

this is the ShowNotes component

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import Spinner from '../components/Spinner';
import Button from '../components/Button';
import BackButton from '../components/BackButton';
import { useNavigate } from 'react-router-dom';

function ShowNotes() {
  const navigate = useNavigate();
    const [notes, setNotes] = useState([]);
    const [loading, setLoading] = useState(false);
    const handleDelete = () => {
      navigate('/');
    };
    
    useEffect(() => {
      setLoading(true);
      axios
        .get('http://localhost:3000/notes')
        .then((res) => {
          setNotes(res.data.notes);
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    }, []);
console.log(notes);
  return (
    <div>
        {loading ? (
        <Spinner/>
      ) : (
      <div className="container mx-auto mt-4">
        <BackButton/>

        <h1 className="flex justify-center text-3xl font-bold mb-4">OUR NOTES</h1>
        <table className="w-full table-auto">
          <thead>
            <tr>
              <th className="px-4 py-2">ID</th>
              <th className="px-4 py-2">TITLE</th>
              <th className="px-4 py-2">BODY</th>
              <th className="px-4 py-2">Actions</th>
            </tr>
          </thead>
          <tbody>
            {notes.map((item,index) => (
              <tr key={item._id}>
                <td className="border px-4 py-2">{index+1}</td>
                <td className="border px-4 py-2">{item.title}</td>
                <td className="border px-4 py-2">{item.body}</td>
                <td className="border px-4 py-2">
                <div className="flex justify-center">
                  <Button color="red-500" hoverColor="red-700" name="Delete" onClick={()=>handleDelete()} />
                  <Button color="blue-500" hoverColor="blue-700" name="Add" />
                  <Button color="purple-500" hoverColor="purple-700" name="Edit"/>
                  <Button color="green-500" hoverColor="green-700" name="Show"/>
                </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>)}
    </div>
  )
}

export default ShowNotes



and this is the Button component(maybe it cause the problem)
function Button(props) {
  const buttonClassName = `bg-${props.color} hover:bg-${props.hoverColor} text-white font-bold py-2 px-4 rounded mr-2`;

  return (
    <button className={buttonClassName}>
      {props.name}
    </button>
  );
}

export default Button;

In React Application API data is displaying but when refreshing page it’s showing error

I am learning coding from last 4months. I got strucked here..
I am creating a food delivery App.
Here i want to display Restaurant Name and menu list in UI..
it’s ok its worked but when i am refreshing the page it’s showing error.
I used react useState and useeffect hook to render

This is my code
When i am refreshing page it’s showing error

Api Data is Displayed

Execute a function when the page (component) loads in Vue 3

Like I wrote in the title, I´m currently looking how to do that. I´m exporting the function from a .js file, but I need that it executes when a specific component is loaded in the UI. In the components Currently I´m working with script setup.

Please help

<script setup>
//Example
import {someFunction} from "./js/allowFunctions.js"
</script>

I tried changing the script setup to only script, but it could take me hours to refactor a lot of code in my proyect

ReactToastify.css.map not found (Next 13 /app folder)

When trying to import the css from the React-tostify lib import 'react-toastify/dist/ReactToastify.css' I get the following error:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/_next/static/css/app/ReactToastify.css.map

I’ve already tried deleting my node_modules, .next, I’m on the latest version of Next (13.4.19) and React-toastify (9.1.3). I’ve tried every possible solution but nothing has worked.

The strange thing is that Toast components work normally for me, as do their styles, whether running Next in development or production. The only error is this message that appears in the console.

Copy Text and Image using clipboard in JS

I am trying to copy an image with a text and paste to slack. It works when i try to copy it to notepad but wont work when i copy the same to slack.

JS code :

const btn = document.getElementById("btn");
const out = document.getElementById("out");


btn.addEventListener("click", async () => {
  try {
    const html = `
      <img src="https://picsum.photos/seed/picsum/200/300">
      <p>Random string</p>
    `;
    
    const data = [
      new ClipboardItem({
        "text/html": new Blob([html], {
          type: "text/html"
        })
      })
    ];

    navigator.clipboard.write(data).then(
      () => {
        out.innerText = "Copied to clipboard!";
      },
      (err) => {
        out.innerText = "Error: " + err;
      }
    );
  } catch (err) {
    out.innerText = "Error: " + err;
  }
});

HTML :

<p>Click Copy, then paste into Word/Teams/Slack</p>


<button id="btn" type="button">Copy HTML (works)</button>

<pre id="out"></pre>

RollupError: “default” is not exported by “node_modules/react/index.js”

Using Rollup for the first time for creating a library, have a basic button component and running into this error when running rollup - c

src/index.ts → dist/esm/index.js…
[!] RollupError: “default” is not exported by “node_modules/react/index.js”, imported by “src/components/Button/Button.tsx”.
https://rollupjs.org/troubleshooting/#error-name-is-not-exported-by-module
src/components/Button/Button.tsx (1:7)
1: import React from “react”;
^
2: const Button = (props) => {

Followed the instructions from the troubleshooting link, installed @rollup/plugin-commonjs but still get this error.

package.json

{
  "name": "button-library",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "rollup": "rollup -c"
  },
  "author": "Leon Gaban",
  "license": "ISC",
  "dependencies": {
    "react": "^18.2.0"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^25.0.4",
    "@rollup/plugin-node-resolve": "^15.2.1",
    "@rollup/plugin-typescript": "^11.1.3",
    "@types/react": "^18.2.22",
    "jest-environment-jsdom": "^29.7.0",
    "rollup": "^3.29.2",
    "rollup-plugin-dts": "^6.0.2",
    "rollup-plugin-postcss": "^4.0.2",
    "tslib": "^2.6.2",
    "typescript": "^5.2.2"
  },
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.js",
  "files": [
    "dist"
  ],
  "types": "dist/index/.d.ts"
}

Rollup config

import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import commonjs from "@rollup/plugin-commonjs";
import postcss from "rollup-plugin-postcss";
import dts from "rollup-plugin-dts";

import packageJson from "./package.json" assert { type: "json" };

export default [
  {
    input: "src/index.ts",
    output: [
      {
        dir: "output",
        format: "cjs",
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      resolve(),
      typescript({ tsconfig: "./tsconfig.json" }),
      postcss(),
    ],
  },
  {
    input: "dist/esm/types/index.d.ts",
    output: [
      {
        file: "build/scripts.js",
        format: "esm",
        sourcemap: true,
        globals: ["react"],
      },
      {
        file: "dist/index.d.ts",
        format: "esm",
      },
    ],
    plugins: [
      commonjs({
        include: "./node_modules/**",
      }),
      dts(),
    ],
    external: [/.(css|less|scss)$/],
  },
];

The Button component

import React from "react";

interface ButtonProps {
  label: string;
}

const Button = (props: ButtonProps) => {
  return <button>{props.label}</button>;
};

export default Button;

Merge 2 arrays at specific indices in Javascript

I have a target array, say: [A, C, E, F, H].
I have another array that needs to be merged (toMerge) to target, say: [B, D, G].
I also have an integer array that tells the indices of target array where *toMerge” items will be merged at, say: [1, 3, 6].

I need a function that will merge toMerge array into target in-place at indices specified by the indices array so that target eventually looks like [A(0), B(1), C(2), D(3), E(4), F(5), G(6), H(7)]

I tried using inbuilt array splice functions to iterate over indices array and splice(add) each at each index. Something along the lines:

for (let i = 0; i < indices.length; i++) {
    target.splice(indices[i], 0, toMerge[i]);
}

I am looking for any solution that can do it more efficiently and elegantly.

Import excel with nested cells (headers) and parse it to json

I need to import an excel file, get the json and draw the same table in my form.

I have used XLSX and XLSX.utils.sheet_to_json(sheet, {header: 1, defval: ''}) , but the problem is in merged cells.

Im trying to parse this excel file

enter image description here

And receiving json data in this form:

[
    ["Item","Index","Params","",""],
    ["","","Value","Style",""],
    ["", "","","Color","Font"],
    ["abc",1,999,"red","bold"],
    ["cas",2,312,"yellow","italic"]
]

I understand that empty string means that the cell is merged, but I can’t understand which cell was merged (neighboring, top, both).

Are there any libraries/other solutions to my problem?

Menu and Submenu Display Mechanism

I want to implement a mechanism to display sub-menus when I click on an item in the main menu of my Angular application.

The issue I’m facing is that when I click on an item in the main menu, like Agences, I want that item to be hidden to make room for the sub-menu, for example, Portefeuilles.

Illustration:

enter image description here

I click on Agences

enter image description here

The Agences section should disappear and make way for the sub-menu.

enter image description here

I’m unable to solve my problem. Could you please guide me on how to resolve it?

online.ts

export class OnlineComponent implements OnInit {
  nav: IMenuItem[] = [];

  constructor(private onlineService: OnlineService) { }

  ngOnInit() {
    // Initialize the 'nav' property with data from the 'onlineService'
    this.nav = this.onlineService.IMenuItem;
  }

  toggleSubMenu(index: number) {
    // Toggle the active state of the clicked item
    this.nav[index].active = !this.nav[index].active;

    // Ensure that all other items are deactivated
    for (let i = 0; i < this.nav.length; i++) {
      if (i !== index) {
        this.nav[i].active = false;
      }
    }
  }
}

online.html

<div class="container text-center" *ngIf="nav">
    <div class="sideBar">
      <div class="menu-content">
        <ul class="menu-items">
          <li class="item" *ngFor="let menuItem of nav; let i = index">
            <div class="menu-item" (click)="toggleSubMenu(i)">
              <!-- Display the menu item name -->
              <span class="title">{{ menuItem.name }}</span>
            </div>
            <ul class="submenu" *ngIf="menuItem.active">
              <li class="subitem" *ngFor="let subItem of menuItem.sub">
                <div class="submenu-item">
                  <!-- Add [routerLink] directive to manage navigation -->
                  <a [routerLink]="subItem.state">{{ subItem.name }}</a>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
  
  <div class="container">
    <!-- This is where the routed components will be displayed -->
    <router-outlet></router-outlet>
  </div>

For your information, my code is available on Stackblitz.

Thank you for your help.

OBS Filter not Toggling when using OBS Websocket

I’ve tried to go about getting the filter in OBS to toggle using OBS websocket in two ways.

The first way is with batch file programming using the OBSCommand.exe command-line tool. Keep in mind, all prerequisite code is already in place. This is just the line of code to run this action:

OBSCommand.exe /server=%localIP%:%OBSWSSerPor% /password=%OBSWSPass% /setsourcefiltervisibility="MS1","Record - MS1",true

This should have selected the source “MS1” and toggled the “Record – MS1” to true. I have tried this without using any space characters.

Without going into much detail, the second way I have tried is via OBS Websocket in an html file with js script. The method I use is basically the same, calling the same command: setsourcefiltervisibility but this method also does not work. The reason I don’t share this method is that I believe the issue is with the setsourcefiltervisibility command. It seems to drop the connection when this command is run.

To my knowledge, I have done all the is required for it to function, but is does not, for either method. The method I would prefer to use is the batch file method, as that is what I am most used to working with. But I would appreciate any help. I will leave the code I used for the second method in a command below this post. Keep in mind I had used ChatGPT for the code creation.

I cannot find the answer to this issue anywhere. I don’t believe it is a syntax issue, but I could be wrong. Thanks for any assistance in advance!