Trouble Accessing Json file in JS [duplicate]

I have an HTML file which I’m running with my chrome browser locally, and a json data file
in the same directory. I want to pull in the data in my JS code in script tag and it isn’t working.

Here is the function in my script tag where the problem is.

async function calculate_pn() {
            var json = await fetch("./roll_data.json").then(r => r.json());
            var pn = document.getElementById("PN").value;
            //find data.
            var od = json[pn]["OD"];
            var core = json[pn]["Core"];
            var curr_od = Number(document.getElementById("PN_OD_current").value);
            var result = (curr_od*curr_od - core*core) / (od*od - core*core);
            document.querySelector(".Result").innerHTML = result;
        }

Here is a copy of my entire html code. I include it all in case you want to copy it and try it yourself.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RollCount</title>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
    <button type="button" onclick="enter_part_number()">Enter Part Number</button>
    <h3>Or</h3>
    <button type="button" onclick="enter_dimensions()">Enter roll dimensions</button>

    <div class="DimensionOptions">
        <label>Outer Diameter</label>
        <input type="text" id="OD">
        <label>Core Size</label>
        <input type="text" id="Core">
        <label>Current Outer Diameter</label>
        <input type="text" id="DIM_OD_current">
        <button type="button" onclick="calculate_dim()">Submit</button>
    </div>

    <div class="PartNumberOptions">
        <label>Part Number</label>
        <input type="text" id="PN">
        <label>Current Outer Diameter</label>
        <input type="text" id="PN_OD_current">
        <button type="button" onclick="calculate_pn()">Submit</button>
    </div>

    <h3 class="Result"></h3>

    <script>
        //hide options when page first loads.
        document.querySelector(".PartNumberOptions").style.visibility = "hidden";
        document.querySelector(".DimensionOptions").style.visibility = "hidden";
        
        //toggle
        function enter_part_number() {
            if (document.querySelector(".DimensionOptions").style.visibility == "visible") {
                document.querySelector(".DimensionOptions").style.visibility = "hidden";
            }
            document.querySelector(".Result").innerHTML = "";
            var input_option = document.querySelector(".PartNumberOptions");
            input_option.style.visibility = input_option.style.visibility == "hidden" ? "visible" : "hidden";
        }

        function enter_dimensions() {
            if (document.querySelector(".PartNumberOptions").style.visibility == "visible") {
                document.querySelector(".PartNumberOptions").style.visibility = "hidden";
            }
            document.querySelector(".Result").innerHTML = "";
            var input_option = document.querySelector(".DimensionOptions");
            input_option.style.visibility = input_option.style.visibility == "hidden" ? "visible" : "hidden";
        }

        function calculate_dim() {
            var od = Number(document.getElementById("OD").value);
            var core = Number(document.getElementById("Core").value);
            var curr_od = Number(document.getElementById("DIM_OD_current").value);
            var result = (curr_od*curr_od - core*core) / (od*od - core*core);
            document.querySelector(".Result").innerHTML = 100*result + "%";
        }

        function calculate_pn() {
            var data = fetch("./roll_data.json");
            var json = JSON.parse(data);
            var pn = document.getElementById("PN").value;
            //find data.
            var od = json[pn]["OD"];
            var core = json[pn]["Core"];
            var curr_od = Number(document.getElementById("PN_OD_current").value);
            var result = (curr_od*curr_od - core*core) / (od*od - core*core);
            document.querySelector(".Result").innerHTML = result;
        }
        
    </script>
</body>

</html>

I tried running the HTML and entering one of the part numbers in my json file and it cannot find the data.

Here is my json file. It is very small.

{
    "01030248":{"OD":8.13,"Core":4.75},
    "01180081":{"OD":2,"Core":1.3125},
    "01180281":{"OD":7.1875,"Core":3.1875},
    "01180300":{"OD":2.75,"Core":1.25},
    "01180372":{"OD":14.25,"Core":3},
    "01188505":{"OD":4.5,"Core":3.1875},
    "01188553":{"OD":6.625,"Core":3.1875},
    "01188629":{"OD":6.875,"Core":3.25},
    "01188630":{"OD":6.875,"Core":3.1875},
    "01188706":{"OD":4.5625,"Core":3.25},
    "01190181":{"OD":11.5,"Core":4},
    "01190182":{"OD":11.5,"Core":4},
    "01030076r":{"OD":13,"Core":3.25}
}

Svelte component not forwarding an event

I have a series of 3 Svelte components, one inside the other, and am trying to forward an event from the innermost to the outermost component. However, the event is only triggered on the second, middle component, and is never triggered on the outermost.

Innermost (TreeNodeView.svelte)

<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import TreeNode from "./TreeNode";
  import TreeView from "./TreeView.svelte";

  const dispatch = createEventDispatcher();

  function onWantsUpload() {
    console.log("TreeNodeView");
    dispatch("wantsUpload", treeNode.id);
  }

  export let treeNode: TreeNode;
</script>

<li>
  </span>
    <span class="upload"
          aria-label={`Upload new version: ${treeNode.text}`}
          role="button"
          on:click={onWantsUpload}
          on:keyup={onWantsUpload}>
      <Upload title={`Upload new version: ${treeNode.text}`} />
    </span>
</li>

Middle (TreeView.svelte)

<script lang="ts">
  import TreeNode from "./TreeNode";
  import TreeNodeView from "./TreeNodeView.svelte";

  export let treeNodes: Array<TreeNode>;
</script>

<ul role="group">
    {#each treeNodes as treeNode ( treeNode.id )}
        <TreeNodeView
          {treeNode}
          on:wantsUpload />
    {/each}
</ul>

Outermost (ProjectDetail.svelte)

<script lang="ts">
  import ProjectDetailModel from "../../../models/ProjectDetail";
  import TreeNode from "../treeView/TreeNode";
  import TreeView from "../treeView/TreeView.svelte";

  export let treeNodes: Array<TreeNode>;
  export let projectDetail: ProjectDetailModel;

  function onWantsUpload(e: CustomEvent<string>) {
    console.log("ProjectDetail");
  }
</script>

<TreeView
  {treeNodes}
  on:wantsUpload={onWantsUpload} />

When I click the Upload element on the innermost component, I expect in the console to see …

TreeNodeView
ProjectDetail

… but all I see is …

TreeNodeView

To debug, I’ve modified the middle component (TreeView.svelte) to explicitly handle and then re-dispatch the event:

<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import TreeNode from "./TreeNode";
  import TreeNodeView from "./TreeNodeView.svelte";

  const dispatch = createEventDispatcher();

  export let treeNodes: Array<TreeNode>;

  function onWantsUpload(e: CustomEvent<string>) {
    console.log("TreeView");
    dispatch("wantsUpload", e.detail);
  }
</script>

<ul role="group">
    {#each treeNodes as treeNode ( treeNode.id )}
        <TreeNodeView
          {treeNode}
          on:wantsUpload={onWantsUpload} />
    {/each}
</ul>

And now, when I click the Upload element on the innermost component, I expect in the console to see …

TreeNodeView
TreeView
ProjectDetail

… but all I see is …

TreeNodeView
TreeView

What have I missed? Why is my outermost component not receiving the event, or why is the middle component not dispatching the event?

Navlink- route not found issue

Our Products

//FileName- allProducts
import React from ‘react’

const AllProducts = () => {
return (
AllProducts
)
}

export default AllProducts;

I am not being redirected to this page as the output is not displayed any suggestions on how do i fix this.

How to pass grouped array to a table?

I Have grouped the array like below :

"2023-10-01" => IlluminateSupportCollection {#1693
      #items: array:2 [
        0 => array:4 [
          "emp_id" => 1
          "name" => "Aruna"
          "code" => "DO"
          "date" => "2023-10-01"
        ]
        1 => array:4 [
          "emp_id" => 2
          "name" => "Aprilia"
          "code" => "EVE"
          "date" => "2023-10-01"
        ]
      ]
      #escapeWhenCastingToString: false
    }
    "2023-10-03" => IlluminateSupportCollection {#1703
      #items: array:2 [
        0 => array:4 [
          "emp_id" => 1
          "name" => "Aruna"
          "code" => "NIG"
          "date" => "2023-10-03"
        ]
        1 => array:4 [
          "emp_id" => 2
          "name" => "Aprilia"
          "code" => "MID"
          "date" => "2023-10-03"
        ]
      ]
      #escapeWhenCastingToString: false
    }
    "2023-10-04" => IlluminateSupportCollection {#1694
      #items: array:1 [
        0 => array:4 [
          "emp_id" => 2
          "name" => "Aprilia"
          "code" => "MID"
          "date" => "2023-10-04"
        ]
      ]
      #escapeWhenCastingToString: false
    }
    "2023-10-05" => IlluminateSupportCollection {#1690
      #items: array:1 [
        0 => array:4 [
          "emp_id" => 2
          "name" => "Aprilia"
          "code" => "MID"
          "date" => "2023-10-05"
        ]
      ]
      #escapeWhenCastingToString: false
    }
    "2023-10-06" => IlluminateSupportCollection {#1689
      #items: array:1 [
        0 => array:4 [
          "emp_id" => 2
          "name" => "Aprilia"
          "code" => "MID"
          "date" => "2023-10-06"
        ]
      ]
      #escapeWhenCastingToString: false
    }
    "2023-10-07" => IlluminateSupportCollection {#1688
      #items: array:2 [
        0 => array:4 [
          "emp_id" => 1
          "name" => "Aruna"
          "code" => "DO"
          "date" => "2023-10-07"
        ]
        1 => array:4 [
          "emp_id" => 2
          "name" => "Aprilia"
          "code" => "DO"
          "date" => "2023-10-07"
        ]
      ]
      #escapeWhenCastingToString: false
    }

I would like to pass the grouped array to my table using Ajax. this is my expected table

ID 2023-10-01 2023-10-02 2023-10-03 2023-10-04 2023-10-05 2023-10-06 2023-10-07
1 DO NIG DO
2 EVE MID MID MID MID DO

Below is my JS code :

$.ajax({
    type: "get",
    url: "{{ route('schedules.fetch-table-schedule') }}",
    dataType: "json",
    success: function (response) {
    $.each(response.result, function( index, value ) {
        var body= $("<tr><td>" + value + "</td></tr>");
        $("#schedule-table #body_schedule").append(body);
    });
}

Sorry, but I don’t have any idea how to do it. Any help would be helpful for me. Thank you so much.

how to extract file from the file input in html

i am trying to extract the file from the file input and , i am also trying that when user click on the sign in button , the content must be downloaded in form of pdf in the user device , i am able to do that , but the file isn’t coming in the pdf .

what i have tried

**hmtl file ** 

     ` <!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
<link rel="stylesheet" href="huehue.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js">                </script>
    <title>File Upload Example</title>
      </head>
 <body>
   <h1>File Upload Example</h1>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <form id="myForm">
    <label for="name">Name:</label><br>
    <input type="text" id="name" name="name" required><br>
    <label for="email">Email:</label><br>
    <input type="email" id="email" name="email" required><br><br>
     <input type="file" name="file" id="file">
     <button type="button" onclick="generatePDF()">Download PDF</button>
   </form>
   <script>
   function generatePDF() {
    const file=document.getElementById('file').value
    const name = document.getElementById('name').value
    const email = document.getElementById('email').value
    const element = document.getElementById('myForm');
     html2pdf().from(` Name : -${name}<br>+" "+`Email- ${email}<br>+""+${file}`).save();
    console.log(name)
    }
   </script>
   </body>
   </html>`

** i am getting the file path , but i want the whole file and it’s content**

Unable to write a polyfill for call function [duplicate]

This is my polyfill for call method

Function.prototype.mycall = (obj,...args)=>{
    if(typeof this!="function") throw new Error("mycall can only be used on a function")
    obj.myFunc = this
    obj.myFunc(...args)
    delete obj.myFunc
}

And this is my whole script including the polyfill


obj = {
    name: "sai",
    age: 25
}

sample = ()=>{
    console.log(`I am ${this.name} and is ${this.age} years old`)
}

Function.prototype.mycall = (obj,...args)=>{
    if(typeof this!="function") throw new Error("mycall can only be used on a function")
    obj.myFunc = this
    obj.myFunc(...args)
    delete obj.myFunc
}


sample.mycall(obj)

But when I look at my console, I am getting this error

task.js:12 Uncaught Error: mycall can only be used on a function
    at Function.mycall (task.js:12:39)
    at task.js:22:8
Function.mycall @ task.js:12
(anonymous) @ task.js:22

Can anyone please help me on why I am getting this error?

In Next.js App router should the page.js be a server component?

In Next.js 13 and above (App router) should the page.js of all the routes/folders be a server component ? I mean is it the standard practice. I know that it can be a client component using use client but is it a good practice or will there be issues during build process.

I also noticed that during build the page.js is taken as server component or something like that. Would be grateful if someone could explain this to me?

Email is not send after submit on form

I have problem with sending email from html form. Somehow when i click submit nothing happens. The validation of fields works nevertheless as mentioned before nothing happens when doing submit button. What could be wrong here?

html part:

<section id="contact">
        <div class="container">
            <h3>Formularz kontaktowy</h3>
            <div class="col-md-6 col-md-offset-3 wow fadeInUp" data-wow-delay=".3s">
                <form role="form" id="contactForm">
                    <div class="row">
                        <div class="form-group">
                            <input type="text" class="form-control" name="name" id="name"
                                placeholder="Wpisz swoje imię, nazwisko" required="required">
                        </div>
                        <div class="form-group">
                            <input type="email" class="form-control" name="email" id="email" placeholder="Enter email"
                                required>
                        </div>
                        <div class="form-group">
                            <textarea id="message" name="message" class="form-control" rows="5"
                                placeholder="Enter your message" required></textarea>
                        </div>
                        <button type="submit" id="form-submit" class="btn-block">Wyślij wiadomość</button>
                        <div class="alert alert-success h4 hidden" id="msgSubmit">
                            <strong>Udało się!</strong> Twoja wiadomość została wysłana poprawnie.
                        </div>
                        <div class="alert alert-danger h4 hidden" id="msgError">
                            <strong>Błąd</strong> Prosimy odświeżyć stronę i spróbować ponownie.
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </section>

Scripts:

<script>
        $(document).ready(function () {
            $("#contactForm").on("submit", function (event) {
                if (event.isDefaultPrevented()) {
                } else {
                    event.preventDefault();
                    submitForm();
                }
            });
        });
        function submitForm() {
            $.ajax({
                type: "POST",
                url: "mail.php",
                data: $("#contactForm").serialize(),
                success: function (text) {
                    if (text == "success") {
                        $("#msgSubmit").removeClass("hidden");
                        setTimeout(function () {
                            $("#msgSubmit").addClass("hidden");
                        }, 6000);
                    }
                },
                error: function () {
                    /* You probably want to add an error message as well */
                    $("#msgError").removeClass("hidden");
                }
            });
        };
    </script>

mail.php file:

<?php
//Required field names array
$required = array('name', 'email', 'message');

//Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
  }
}

if ($error) 
    {
       echo "invalid";  //Was empty values should not be reached as html form inspecting it as well
    } 
else 
    {   
        $name = $_POST["name"];
        $email = $_POST["email"];
        $message = $_POST["message"];
 
        $EmailTo = "[email protected]";
        $Subject = $name;
 
        $message .= "nn" . 'From: '. $email;
        $success = mail($EmailTo, $Subject, $message);
 
        //Results catched by AJAX
        if ($success){
        echo "success";
        }else
        {
        echo "invalid";
        }    
    }
?>

Next.js, ReferenceError: sessionStorage is not defined during build

I’m using Next.js 13 App router. I was storing the JWT token I received on login in session storage. I was able to access the token in all of my page.js pages in all of my routes if the page.js for that specific route/folder was a client component. This worked fine during dev, ie when i ran with npm run dev , but when i took the build , ie, next build it failed and gave me the error ReferenceError: sessionStorage is not defined .

Is it necessary that in Next.js the page.js for every route be server components rather than client. Are they considered as server components during build??

“@vitejs/plugin-react can’t detect preamble. Something is wrong.” console message with flask-vite and React

I wanted to use flask-vite to add some React components to my app.

I started by using the flask-vite Flask plugin to add Vite to my Flask project.

Then I installed React and carefully updated the configuration files, using a freshly created React project that I made with Vite as a reference.

I couldn’t get my React components to show up, and the only clue was this console message:

@vitejs/plugin-react can't detect preamble. Something is wrong.

I searched for this message and found lots of pages that weren’t very helpful.

Each child in a list should have a unique “key” prop — but they already do (two children per iteration)

This question is unlike similar ones because as far as I can tell, all other questions of this nature really do not have unique keys for all children being map‘d.

Here is my code…

First, for good measure, I have this check, so there can be no doubt that each key is unique:

    const nbItems = items.length
    const nbUniqueUuids = new Set(items.map((item) => item.uuid)).size
    if (nbItems !== nbUniqueUuids) {
        throw new Error("Non-unique UUIDs detected")
    }

Then, I do this in the return statement of the component:

{items.map((item, index) => {
                return (
                    <>
                        {index !== 0 && (
                            <Xarrow
                                key={`${item.uuid}-arrow`}
                                start={item.uuid}
                                end={items[index - 1].uuid}
                            />
                        )}
                        <Item
                            key={item.uuid}
                            action={item}
                        />
                    </>
                )
            })}

As you can see, two elements are rendered: An Xarrow and an Item. However, each has its own key: one with a -arrow suffix, and one without. The uuid property is confirmed unique, or the if-statement would have triggered and thrown an error.

Why does React think there’s a non-unique child here, when clearly, each child has a unique key?

The exact error message is: Warning: Each child in a list should have a unique "key" prop. Check the render method of MyExampleComponent. “MyExampleComponent” here is confirmed to be this one. Neither Xarrow nor Item render any children.

If I wrap both items in a div and give it the key, it works, but I don’t want to do that.

I will also note that this works as it should, but I still get the error in the console.

How do you make an HTML element transition seamlessly across pages like Stack Overflow’s top bar?

When you move from one page to another on a website, some of the content disappears briefly before being replaced by the contents of the new page. But other elements seem not to be affected at all. For example when navigating this website (Stack Overflow), across pages, the top bar div doesn’t flinch.

How can this effect be achieved? Preferably with vanilla HTML, CSS and JS. Can it be done without combining all the pages into one file?

How did Stack Overflow do it with their top bar?

Sveltekit redirect is not working from server side function

I’ve got a svelte Header component. In this component there’s a logout button. When the button is clicked a function is invoked and this function calls a server side function. In this function I’ve got a redirect statement that doesn’t seem to work.

Here’s part of the component (pasting only relevant code):

<script>

    /**
     * Logs out the current user.
     * @returns {Promise<void>}
     */
    const logout = async () => {

        // call to internal API to perform logout.
        const response = await fetch("/api/user-logout", {
            method: "POST",
        });
    }

</script>

<header>
<!-- Logout -->
            <div class="tooltip tooltip-left" data-tip="Log out">
                <button
                        on:click={logout}
                        class="relative p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 focus:bg-gray-100 focus:text-gray-600 rounded-full"
                >
                    <span class="sr-only">Log out</span>
                    <svg aria-hidden="true" class="h-6 w-6" fill="none" stroke="currentColor"
                         viewBox="0 0 24 24">
                        <path d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" stroke-linecap="round" stroke-linejoin="round"
                              stroke-width="2"/>
                    </svg>
                </button>
            </div>
</header>

Here’s api/user-logout/+server.js:

import { redirect } from "@sveltejs/kit";

export async function POST({ request, fetch, cookies, event}) {

    // remove the auth cookie.
    // cookies.delete(AUTH_TOKEN_KEY, { path: '/' });

    // redirect user to login page.
    throw redirect(302, '/login');
}

The above function is being hit for sure as I added some log statements and they are being printed but the redirect never happens.

I also tried using only redirect(302, '/login') as I’m using sveltekit 2.5 but didn’t work.

I made it work by returning a response from api/user-logout/+server.js and then using goto in the frontend function:

const logout = async () => {

        // call to internal API to perform logout.
        const response = await fetch("/api/user-logout", {
            method: "POST",
        });

        if (await response.status == 200) {
             await goto("/login")
        }
    }

It works but I’d rather have the redirect from api/user-logout/+server.js.

What am I missing?

Please tell me. What is this error means? [closed]

Warning: Undefined array key “newDate” in C:xampphtdocsCreate-examtest.php on line 181
Dates updated successfully

I dont understand the error. what is the newDate

I want to show mysql table on the html table and i created a input field to change date in the date column. i want to change it in mysql also. how to do that.

How to cleanly “close”/”abort” a webscoket connection before it connects

I am making a ws connection, but some cases want to abort the request, without the console logging an error –

WebSocket connection to ‘ws://xyz:3001/? failed: WebSocket is closed
before the connection is established.

the code looks like:

const ws = new WebSocket(`${xyz}`);

setTimeout(() => ws.close(), random); // some other event that occur at any given time "random"

A simple use case is if a connection is initiated when a user opens a view, but then quickly closes the view which could/should abort the connection request.

is there a way to abort the connection request cleanly, so that I don’t get too many logs like that in the browser console?