Console log not printing response from the server via fetch()

I am using a script to send transactions from my card website to localhost, which is accurately receiving it and also successfully sends a json response but after that console.log isn’t displaying it at all. I can check the response on network tab in dev tools but just curious what’s the reason for not printing json response.

async function sendData(username, transactions) {
  let apiUrl = "http://localhost:3100/api";
  let postOptions = {
    method: "POST",
    cache: "no-cache",
    headers: {
      "Content-Type": "application/json",
    },
    redirect: "follow",
    referrerPolicy: "no-referrer",
    body: JSON.stringify({ username, transactions }),
  };

  try {
    let response = await fetch(apiUrl, postOptions);
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }
    let serverMessage = await response.json();
    console.log(serverMessage);
  } catch (error) {
    console.log(error.message);
  }
}

I even tried without async as following but still nothing printed.

function sendData(username, transactions) {
  let apiUrl = "http://localhost:3100/api";
  let postOptions = {
    method: "POST",
    cache: "no-cache",
    headers: {
      "Content-Type": "application/json",
    },
    redirect: "follow",
    referrerPolicy: "no-referrer",
    body: JSON.stringify({ username, transactions }),
  };

  fetch(apiUrl, postOptions)
    .then((res) => res.json())
    .then((msg) => console.log(msg))
    .catch((e) => console.log(e));
}

One Clarification:
When I run the same code (with some triggering front end of course) in a JS injector chrome extension (e.g; scripty), it then prints the response, but not when I call it manually in console.

How can I create a dynamic form in JavaScript that adds/removes input fields based on user interaction?

I’m working on a form where users need the ability to dynamically add or remove input fields based on their actions. Specifically, I want to create a form that starts with one input field and allows users to add new input fields by clicking an “Add Input” button, and remove the last added input field by clicking a “Remove Input” button.

I’ve tried using JavaScript to add and remove the input fields, but I’m not sure if I’m doing it correctly or if there’s a more efficient way to handle this. Below is the HTML and JavaScript code I’ve written so far.

<form id="dynamicForm">
  <div id="inputContainer">
    <input type="text" name="inputField[]">
  </div>
  <button type="button" id="addInput">Add Input</button>
  <button type="button" id="removeInput">Remove Input</button>
</form>
const addButton = document.getElementById('addInput');
const removeButton = document.getElementById('removeInput');
const inputContainer = document.getElementById('inputContainer');

addButton.addEventListener('click', function() {
  const newInput = document.createElement('input');
  newInput.type = 'text';
  newInput.name = 'inputField[]';
  inputContainer.appendChild(newInput);
});

removeButton.addEventListener('click', function() {
  const inputs = inputContainer.getElementsByTagName('input');
  if (inputs.length > 1) {
    inputContainer.removeChild(inputs[inputs.length - 1]);
  } else {
    alert('At least one input field is required!');
  }
});

How can I structure a Javascript object to record colour themes for seven items

I have an LED clock with the following elements that can take an RGB value

  1. C for Cardinal points (ie 3,6,9,12 hrs or 15,30,45,60 mins)
  2. F for One hour/Five minute points (ie 1,2,4,5,7,8,10,11 hrs or 5,10,20,25,35,40,50,55 mins)
  3. H for Hour hand
  4. M for Minute hand
  5. CF for all points at night (Hour points AND Cardinal points, combined)
  6. Hn for Hour hand at night
  7. Mn for Minute hand at night

I want to create a few themes, so I want to create a JavaScript theme object that stores the seven RGB values and then populate named instances of it with RGB values. I’m doing this in NodeRed and the idea is that a user can pick one of the themes from a list in the NodeRed dashboard, which will publish 7 MQTT topics each containing a payload of the relevant part of the theme object. An ESP32 subscribes to those topics and colours the correct LEDs according to the payload RGB value. I am struggling to decide how to efficiently construct the theme object. So far, I’ve got:

let theme = {
  themeName: "",
  C:[R,G,B],
  F:[R,G,B],
  H:[R,G,B],
  M:[R,G,B],
  CF:[R,G,B],
  Hn:[R,G,B],
  Mn:[R,G,B]
}

Is this along the right lines and do I populate the R, G & B values with a default set or is there a way to specify the object without values. Also, do I need to declare the R,G & B type int

Textarea not resizing correctly on input in JavaScript

I am trying to create a <textarea> that automatically resizes based on the content inside it. However, it sometimes grows too large, larger than the content is.

I am using tailwind in the code, I am testing it in Firefox if it helps.

I have tried resizing font size. It actually helped when the font is big enough, but of course that is not a final solution. Tried few other dumb stuff, then realized that it probably isn’t the JavaScript code that is wrong and I have probably some problems in the TailwindCSS part.

There is my code:

msgBox.addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight + 'px';
});
body {
  background: black;
}

textarea {
  background: darkblue;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">

<textarea id="msgBox" maxlength="1024" class="flex-1 px-3 py-2 h-10 text-white rounded-lg border border-black resize-none min-h-10 focus:outline-none" style="max-height: 100px; overflow-y: auto; box-sizing: border-box;" placeholder="Text here"></textarea>

Cannot read properties of undefined (reading ‘price’) – React

I have an application in react being developed and I have the following error when the application tries to execute a method

Cannot read properties of undefined (reading ‘price’)
at getTotalCartAmount (StoreContext.jsx:33:47)

const getTotalCartAmount = () => {
let totalAmount = 0
for (const item in cartItems) {
if (cartItems[item] > 0) {
let itemInfo = product_list.find((product) => product.id === item)
totalAmount += itemInfo.price * cartItems[item]
}

    }

return totalAmount
}

I believe it is a synchronization problem, but I can’t understand where the method should synchronize

I believe it is a synchronization problem, but I can’t understand where the method should synchronize

Taking specific values in a JSON file and make another JSON file with extracted

I have a JSON file that is taken from the data of the project. However, there are information in it that I do not need for my specific goal. This is the JSON data:

const toSql = [
    
    {"id":1,"battlerName":"Actor1_1","characterIndex":0,"characterName":"Actor1","classId":1,"equips":[2,0,0,3,0],"faceIndex":0,"faceName":"Actor1","traits":[{"code":51,"dataId":2,"value":1},{"code":51,"dataId":4,"value":1}],"initialLevel":1,"maxLevel":99,"name":"Reid","nickname":"","note":"","profile":""},
    {"id":2,"battlerName":"Actor1_2","characterIndex":1,"characterName":"Actor1","classId":1,"equips":[1,0,0,9,0],"faceIndex":1,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Priscilla","nickname":"","note":"","profile":""},
    {"id":3,"battlerName":"Actor1_3","characterIndex":2,"characterName":"Actor1","classId":5,"equips":[31,0,65,5,0],"faceIndex":2,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Gale","nickname":"","note":"","profile":""},
    {"id":4,"battlerName":"Actor1_4","characterIndex":3,"characterName":"Actor1","classId":5,"equips":[31,0,0,5,0],"faceIndex":3,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Michelle","nickname":"","note":"","profile":""},
    {"id":5,"battlerName":"Actor1_5","characterIndex":4,"characterName":"Actor1","classId":2,"equips":[7,0,0,20,0],"faceIndex":4,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Albert","nickname":"","note":"","profile":""},
    {"id":6,"battlerName":"Actor1_6","characterIndex":5,"characterName":"Actor1","classId":2,"equips":[7,0,65,21,0],"faceIndex":5,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Kasey","nickname":"","note":"","profile":""},
    {"id":7,"battlerName":"Actor1_7","characterIndex":6,"characterName":"Actor1","classId":3,"equips":[7,0,0,20,0],"faceIndex":6,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Eliot","nickname":"","note":"","profile":""},
    {"id":8,"battlerName":"Actor1_8","characterIndex":7,"characterName":"Actor1","classId":3,"equips":[7,0,0,20,0],"faceIndex":7,"faceName":"Actor1","traits":[],"initialLevel":1,"maxLevel":99,"name":"Roza","nickname":"","note":"","profile":""}
    ]

However, I just need the following: id and traits

How would I go around extracting those two only and make it as another json file?

wait two async calls to complete using NGXS dispatch

When you pass an array of actions (both an async call to an API) to the dispatch method in NGXS, does the dispatch method in NGXS internally use the forkJoin operator from RxJS to process the actions?

Given the example below, will the map operator be triggered when both actions complete?

@Action(User.Get)
public get(ctx: StateContext<UserStateInterface>) {
    return ctx.dispatch([new User.GetUserAccount(), new User.GetUserAddress()])
    .pipe(
        map(([userAccount, userAddress]) => {
            return {
                userAccount,
                userAddress
            }
        })
    )
}

Is there a better aproach?

Laravel + vite + jQuery + tablesorter

I’m a bit junior in vite/npm and I have trouble loading all of the components. The PHP framework is Laravel 11 + Blade + vite.

The layout file contains jQuery in the head section (I had nearly the same JS loading issues, so I’ve kept is there since I use it in many places):

      <script type="text/javascript" src="{{ asset('assets/jquery/jquery.min.js') }}"></script>
        <script type="text/javascript">
            window.jQuery = window.$;
        </script>

        @stack('header_scripts')

        <!-- Scripts -->
        @vite(['resources/css/app.css', 'resources/js/app.js'])

The app.js:

import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.start();

import 'jquery-datetimepicker';
// datetimepickerFactory($);

import 'tablesorter/dist/css/theme.dropbox.min.css';
import 'tablesorter/dist/js/jquery.tablesorter.combined.min.js';

And in my view file I’ve this:

@push('scripts')
    <script type="module">
        document.addEventListener("DOMContentLoaded", () => {
            jQuery("#users-table").tablesorter({
              ....
            });
        });
            </script>
    @endpush

The stack('scripts') is the last line before the closing /body tag in the layout file.

Upon page render I get enrollments:345 Uncaught TypeError: jQuery(...).tablesorter is not a function at HTMLDocument.<anonymous> and I can’t figure out why (npm run dev is running, also tried running ‘npm run build’)

Please help me understand the whole loading mechanism and how to fix the issue properly.

(I’ve tried putting jQuery into app.js, but than I was not able to load jquery-ui properly – seemed that jQuery-ui was not able to recognize jQuery upon init so it bailed out)

Why is Replicate’s API returning a empty object instead of the image URL, and how can I process it?

I am working on an AI-powered image generation app using Replicate’s API, and I’m using the bytedance/sdxl-lightning-4step model to generate images from prompts. However, when I call the /api/generate-image endpoint I created, the API response give me empty result in console.

Here’s the full behavior:

  1. For testing purpose I am just using a given prompt ‘VdoScript’ and only calling GenerateImage methid by clicking the button ‘Create Video’ using onCreateClickHandler method. So you can ignore the other functions if you want, I am just talking about the GenerateImage() function.

I send a POST request with a prompt to /api/generate-image.

"use client"
import React, {useState} from 'react'
import SelectTopic from './_components/SelectTopic'
import SelectStyle from './_components/SelectStyle';
import SelectDuration from './_components/SelectDuration';
import { Button } from '@/components/ui/button';
import axios from 'axios';
import CustomeLoading from './_components/CustomeLoading';
import { v4 as uuidv4 } from 'uuid';

const VdoScript = [
    {
        "scene": 1,
        "duration": 5,
        "ContentText": "1799: Napoleon's army discovers a mysterious stone in Egypt.  Inscriptions in three scripts – hieroglyphs, Demotic, and Ancient Greek – hint at unlocking a lost world.",
        "imagePrompt": "Realistic photo of a weathered stone slab with hieroglyphs, Demotic script, and Ancient Greek script clearly visible, partially buried in sand, bright desert sun, Napoleon's soldiers in the background,  cinematic lighting"
      },
]


function CreateNew() {

    const[formData, setFormData] = useState([]);
    const[loading, setLoading] = useState(false);
    const[videoScript, setVideoScript] = useState();
    const[audioFileUrl, setAudioFileUrl] = useState();
    // saving the captions, words in one state
    const[captions, setCaptions] = useState();
    const[imageList, setImageList] = useState();

    const onHandleInputChange = (fieldName, fieldValue) => {
        console.log(fieldName, fieldValue)

        setFormData(prev=>({
            ...prev,
            [fieldName]:fieldValue
        }))
    }

    const onCreateClickHandler=()=>{
        //GetVideoScript();
        //GenerateAudioFile(ScriptData);
        // GenerateAudioCaption(FILEURL);
        GenerateImage();
    }
    // Get Video Script -- API call
    const GetVideoScript=async ()=>{
        setLoading(true)
        const prompt='Write a script to generate a '+formData.duration+' video on the topic: '+formData.topic+' along with AI image prompt in '+formData.imageStyle+' format for each scene and give me result  in JSON format with image prompt and ContentText as field'
        console.log(prompt)
        const result=await axios.post('/api/get-video-script',{
            prompt:prompt
        }).then(resp=>{
            //console.log(resp.data.result)
            console.log("EXE");
            setVideoScript(resp.data.result); // once scripts is generated
            resp.data.result&&GenerateAudioFile(resp.data.result); // generate the audio file
        })
        //setLoading(false)
        //console.log(result)
    }

    const GenerateAudioFile=async(videoScriptData)=>{
        setLoading(true);
        let script= '';
        const id = uuidv4();
        videoScriptData.forEach(item=>{
            script=script+item.ContentText+' ';
        })
        await axios.post('/api/generate-audio',{
            text:script,
            // for example purpose
            //text:videoScriptData,
            id:id
        }).then(resp=>{
            //console.log(resp.data);
            setAudioFileUrl(resp.data.result);// get file url
            resp.data.result&&GenerateAudioCaption(resp.data.result)
            //setLoading(false);
        })
        // console.log(script);
        //console.log(videoScript, captions, audioFileUrl);
        
    }

    const GenerateAudioCaption=async(fileUrl)=>{

        setLoading(true);
        console.log(fileUrl)
        await axios.post('/api/generate-caption',{
            audioFileUrl:fileUrl
        }).then(resp=>{
            console.log(resp.data.result);
            setCaptions(resp?.data?.result); // generate caption
            GenerateImage();
        })
        
        console.log(videoScript, captions, audioFileUrl);
    }

    /** 
     Used to generate Ai images
    **/
    const GenerateImage=()=>{
        //setLoading(true)
        let images = [];
        // VdoScript for testing...declaired above
        VdoScript.forEach(async(element)=>{
            await axios.post('/api/generate-image',{
                prompt:element?.imagePrompt
            }).then(resp=>{
               console.log(resp.data.result);
               images.push(resp.data.result);
            })
        })
        console.log(images);
        setImageList(images);
        //console.log(imageList)
        setLoading(false);
        
    }

    

  return (
    <div className='mid:px-20'>
        <h2 className='font-bold text-4xl text-primary text-center'>Create New</h2>

        <div className='mt-10 shadow-md p-10'>
            {/* select topic */}
            <SelectTopic onUserSelect={onHandleInputChange}/>

            {/* select style */}
            <SelectStyle onUserSelect={onHandleInputChange}/>

            {/* select duration */}
            <SelectDuration onUserSelect={onHandleInputChange}/>

            {/* create button */}
            <Button className='mt-10 w-full' onClick={onCreateClickHandler}>Create Video</Button>
        </div>

        <CustomeLoading loading={loading}/>

    </div>
  )
}

export default CreateNew
  1. I am calling the API from the path app/api/generate-image/route.jsx: its a model named bytedance/sdxl-lightning-4step (text to image generator ) from replicate.com
import Replicate from "replicate";
import { NextResponse } from "next/server";
import { storage } from "@/configs/FirebaseConfig";
import { getDownloadURL, ref, uploadString } from "firebase/storage";

export  async function POST(req){
    try{
        const {prompt} = await req.json();
        const replicate = new Replicate({
            auth:process.env.REPLICATE_API_TOKEN
        });

        const input = {
            prompt:prompt,
            height:1280,
            weidth:1024,
            num_outputs:1
        };

        const output = await replicate.run("bytedance/sdxl-lightning-4step:5599ed30703defd1d160a25a63321b4dec97101d98b4674bcc56e41f62f35637", { input });
        console.log(output);
        return NextResponse.json({'result':output[0]});

    }catch(e){

    }
}


browser console


postman (showing empty object) console


replicate-api dashboard (showing the model is generating the image)

I think that there is a some problame in the GenerateImage() function.
Expected output should be like that:

{
  "result": "https://path-to-generated-image.com/image.png"
}

but I am getting

{
  "result": {}
}

Can anyone help me , what’s the problem ?

Prior knowledge for dash.js projects? [closed]

What do I need know/learn before getting into dash.js? I’m a telecommunications student and I need to prepare myself for a dash.js project. I have basic knowledge of HTML and JS. Right now, I’m reading about TCP protocol, and asking myself if I even need all those details. Thank you.

react useRef on component unmount

I am making a social media app and I want to save the last scrollTop of a div in a component before the user changes the page and the component unmounts.

I tried doing this to save the scroll position before unmounting but the myRef is null :

  useEffect(()=>{
        return ()=>{
            saveToDb(myRef.current.scrollTop);
        }
    }, []);

How can I do this?

Chart.js LinearScale declaration in Import statement throws warning in VS Code

I have working v4.4.6 Chart.js code implemented in vanilla JS. It’s using an import statement for tree shaking thus:

import {Chart, LineController, LineElement, PointElement, CategoryScale, LinearScale, Filler} from "chart.js"; (the full path to “chart.js” is specified in an import map)

I then have the following registrations later in the code just before I build the chart:

Chart.register(LineController, LineElement, PointElement, CategoryScale, LinearScale, Filler);

It all works fine, but VS code is greying out LinearScale in the import statement with the warning ‘LinearScale’ is declared but its value is never read. ts(6133).

If I remove LinearScale from either the import or registration statements, (or both), then the chart breaks with the error “linear” is not a registered scale as you would expect. So clearly LinearScale is being used somewhere, but VS Code thinks it isn’t? All the other imports and registrations work fine with no warnings. What could be happening here please, and how would I remove this warning? Here’s the relevant map code:

    const elCanvas = document.getElementById(canvasId);
    const data = {
        labels: arLabels,
        datasets: [{
            borderWidth: 1,
            data: arData,
            backgroundColor: function(context) {
                const chart = context.chart;
                const {ctx, chartArea} = chart;
                if (!chartArea) {
                  // This case happens on initial chart load
                  return;
                }
                return getGradient(elCanvas, ctx, chartArea);
            },
            fill: true,
            pointRadius: 0,  // removes rounded blobby peaks
            cubicInterpolationMode: 'monotone'  // prevents smoothing of peaks
        }]
    };

    const options = {
        scales: {
            x: {        
                beginAtZero: true,
                ticks: {
                    callback: function(value, index, ticks) {
                        return `${this.getLabelForValue(value)} Km`;
                    }
                }
            },
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value, index, ticks) {
                        return `${this.getLabelForValue(value)} m`;
                    }
                }
            }
        },
        responsive: false,
        maintainAspectRatio: false,
        animation: false
    };

    const config = {
        type: 'line',
        data: data,
        options: options
    };

    Chart.register(LineController, LineElement, PointElement, CategoryScale, LinearScale, Filler);
    new Chart(elCanvas, config);

Remove class when element focus is removed, However only works when I shift tab instead of tab to new element. (left but not right)

I have an html with some children basically a menu but 2 elements have a submenu

<div class="menu-main-menu-container">
<ul id="menu-main-menu" class="header_menu">
<li id="menu-item-919" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-919"><a href="#nogo">Services</a>
<ul class="sub-menu">
    <li ...>
</ul>
<li ...<a href="#nogo">Plans</a>
<ul class="sub-menu"> ...

THe issue is when I try to remove the class active to the sub menu using JS it only works in one direction! I know menu parent selects the 2 a tags I’m trying to target for losing focus. I know menuChild accesses the child UL element.

document.querySelectorAll('.header_menu > li:has(> ul) > a').forEach((menuParent) => {
    // Find the focused menu item (the 'a' element that is focused)
    if (!menuParent) return;


    const menuChild = menuParent.closest("li").querySelector("ul.sub-menu");
    const subMenuChild = menuChild ? menuChild.querySelectorAll(":scope > li") : [];

menuParent.addEventListener('focusout', (event) => {
    setTimeout(() => {
        // Check if focus has moved outside the submenu or its children
        const activeElement = document.activeElement;
        const isFocusInsideSubMenu = menuChild.contains(activeElement);

        // If focus has moved outside the submenu, close it
        if (!isFocusInsideSubMenu) {
            toggleMenu(menuChild, subMenuChild)

        }
    }, 0); // Delay to allow focusout event to complete
}, true); // Use the capture phase to catch all focus changes

The major issue is the isFocusInsideSubMenu it only goes false when I tab to left i see it in logs. Sometimes works If i click off, but it’s just so inconsistent. Would honestly be fine if was broken the other way.

Update, Has something to do with my addeventlistener I just realized I need to run it on the document rather than one element!!