Cant get value of an input

I dont know if this is an bug or something. I have tried everything but I cant get the value of this input, but if I type the exact same code in console, then it somehow works.

<input class="form-control needed-field" id="myid" name="varname">
var input = document.getElementById("myid").value

I have tried to save the input to a variable then then from the variable get the value because I saw that as a solution on the internet, but that also didnt work.

Comparing multiple values in JSON array and finding the smallest one with javascript

Unfortunately, this is the first time I’ve come across JS, so there are difficulties.

I have an array similar to this one:

{
    "online": [
        {
            "name": "Ivan",
            "id": "321-g90yy-fr91n",
            "id2": 1111,
            "status": "works",
            "position": "editor",
            "online": "yes",
            "login": "ivan2022",
            "Count": 2,
            "Started": 1650047979
        },
        {
            "name": "Jade",
            "id": "566-t32hh-ft01n",
            "id2": 3333,
            "status": "works",
            "position": "editor",
            "online": "yes",
            "login": "jade2022",
            "Count": 1,
            "Started": 1650017979
        },
        {
            "name": "Georg",
            "id": "123-g22tt-fr11n",
            "id2": 222,
            "status": "works",
            "position": "editor",
            "online": "yes",
            "login": "georg2022",
            "Count": 2,
            "Started": 1650042979
        }
    ]
}

I need to use FOR and IF to find which of the users has the minimum “Count” value, if there are multiple users with the same “Count” value then I need to find which one has the lower “Started” value and give the result “id2” and “name” without using console.log.

Any ideas how to do it?

JavaScript FormData() access file body

I have HTML form with file upload input. The form data are stored in a FormData() object so I can send it later to the server using AJAX.

What I’m trying to do is to access the FormData() values so I can modify the file content itself that appear in the request for example in Web Developer Tools -> Network.

If I’m uploading a .txt file or image, I want to be able to read its content, modify it and re-append it to the FormData().

My code so far is able to show the File object but I have no clue how to access its content.

for( var pair of myFormData.entries() ){

   /* pair[1] is the file object inside the FormData */
   console.log(pair[0], pair[1]);

}

Thank you.

Adding a single array into an array of a multidimensional array in Excel Scripts/ Javascript

looking to add a single array into a multidimensional array or an array of arrays.

for example:

Data = ["A","B","C","D"];

NewData =[[1,2,3,4],[5,6,7,8],[9,10,11,12]];

CombinedData = [];

for(i=0; i< NewData.length; i++){
  CombinedData.push(...Data,NewData[i]);
}

However the above results in this:
“CombinedData =[[“A”,”B”,”C”,”D”],[1,2,3,4],[“A”,”B”,”C”,”D”],[5,6,7,8],[“A”,”B”,”C”,”D”],[9,10,11,12],[“A”,”B”,”C”,”D”]….]”

Where what I am looking for is this:
“CombinedData =[[“A”,”B”,”C”,”D”,1,2,3,4],[“A”,”B”,”C”,”D”,5,6,7,8],[“A”,”B”,”C”,”D”,9,10,11,12],]”

This is in ExcelScripts or office scripts which I know is pretty new but just looking for some sort of direction.

on click event with JavaScript doesn’t work in Django

this is the code for (cart.js) in the static/js folder

var updateBtns = document.getElementsByClassName('update-cart')

for (i = 0; i < updateBtns.length; i++) {
    updateBtns[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)
        
    })
}

and in the HTML file in the bottom:

<button data-product="{{ product.id }}" data-action="add"
                class="update-cart btn btn-outline-secondary add-btn ">Add to Cart</button>

and call the js in main.html

<script type="text/javascript" src="{% static 'js/cart.js' %}"> </script>

and I add static in the setting.py, and everything correct.

and everything working well, when I try to (console.log) without a button click event…
the problem is only with the button event because it doesn’t work

CORS PST request works in IIS Express but not IIS

I am having a CORS issue on an IIS web server. I am able to run the below code on my local dev machine running IIS Express (changing appropriate ports and URLs) but I am getting a cors error when I try an access the app once its deployed. The error (I know all over the internet) is

Access to fetch at ‘https://example.com:5001/api/Person/PostPerson’
from origin ‘https://example.com:44337’ has been blocked by CORS
policy: Response to preflight request doesn’t pass access control
check: No ‘Access-Control-Allow-Origin’ header is present on the
requested resource. If an opaque response serves your needs, set the
request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

I am working on a .NET core 5.0 C# Web API app project. Below is my Person model that I am trying to POST.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Below is my person controller

[Route("api/[controller]/[action]")]
[ApiController]
public class PersonController : ControllerBase
{
    private JsonSerializerSettings _jsonSettings;

    [EnableCors("mypolicy")]
    [HttpPost]
    public string PostPerson([FromBody]Person person)
    {
        return JsonConvert.SerializeObject("success", _jsonSettings);
    }
}

Below is the startup.cs methods.

ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder => builder.WithOrigins("https://localhost:44363").AllowAnyHeader());
            options.AddPolicy("mypolicy", builder =>
                builder.WithOrigins("https://example.com:44337").AllowAnyHeader());
        });

Configure method

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseCors();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors("mypolicy");
            });
        }

I also checked connectivity to the api from my laptop using Postman

enter image description here

I appreciate your time, Thanks!

Alpine Expression Error: myComponent is not defined / Uncaught ReferenceError: myComponent is not defined

I’d like to transpose this barchart to Laravel.
So I create an Alpine.js component to handle the buttons and show it in Laravel as you can see in this fiddle.

Original code:

<button onclick="update(data1)">Variable 1</button>
<button onclick="update(data2)">Variable 2</button>

Modified code:

<div x-data="myComponent()">
  <button x-on:click="update(data1)">Data 1</button>
  <button x-on:click="update(data2)">Data 2</button>
</div>

And part of the original JavaScript:

// A function that create / update the plot for a given variable:
function update(data) {

  // Update the X axis
  x.domain(data.map(function(d) { return d.group; }))
  xAxis.call(d3.axisBottom(x))

  // Update the Y axis
  y.domain([0, d3.max(data, function(d) { return d.value }) ]);
  yAxis.transition().duration(1000).call(d3.axisLeft(y));

  // Create the u variable
  var u = svg.selectAll("rect")
    .data(data)

  u
    .enter()
    .append("rect") // Add a new rect for each new elements
    .merge(u) // get the already existing elements as well
    .transition() // and apply changes to all of them
    .duration(1000)
      .attr("x", function(d) { return x(d.group); })
      .attr("y", function(d) { return y(d.value); })
      .attr("width", x.bandwidth())
      .attr("height", function(d) { return height - y(d.value); })
      .attr("fill", "#69b3a2")

  // If less group in the new dataset, I delete the ones not in use anymore
  u
    .exit()
    .remove()
}

And part of the modified Alpine version:

function myComponent(){ // Component
    return { // Object
    update(data){ // Method
      // Update the X axis
      x.domain(data.map(d => d.group))
      xAxis.call(d3.axisBottom(x))

      ...
    }
  }
}

As you can see in the fiddle it works as expected. When we click on the button Data 1 it shows the chart with the data 1 and when we click on the Data 2 it shows the chart with the data 2.

Nevertheless when I transpose it to Laravel just like in the fiddle it doesn’t work:

File dashboard.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">

                        <div x-data="myComponent()">
                          <!-- Add 2 buttons -->
                          <button x-on:click="update(data1)">Data 1</button>
                          <button x-on:click="update(data2)">Data 2</button>
                        </div>

                        <!-- Create a div where the graph will take place -->
                        <div id="my_dataviz"></div>

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

</x-app-layout>

<script src="{{ asset('js/data.js') }}" defer></script>

File data.js:

import * as d3 from 'd3';

// create 2 data_set
const data1 = [
   {group: "A", value: 4},
   {group: "B", value: 16},
   {group: "C", value: 8}
];

const data2 = [
   {group: "A", value: 7},
   {group: "B", value: 1},
   {group: "C", value: 20},
   {group: "D", value: 10}
];

// set the dimensions and margins of the graph
const margin = {top: 30, right: 30, bottom: 70, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
const svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

// Initialize the X axis
const x = d3.scaleBand()
  .range([ 0, width ])
  .padding(0.2);
const xAxis = svg.append("g")
  .attr("transform", `translate(0,${height})`)

// Initialize the Y axis
const y = d3.scaleLinear()
  .range([ height, 0]);
const yAxis = svg.append("g")
  .attr("class", "myYaxis")


function myComponent(){ //Component
    return { //Object
    update(data){ //Method
      // Update the X axis
      x.domain(data.map(d => d.group))
      xAxis.call(d3.axisBottom(x))

      // Update the Y axis
      y.domain([0, d3.max(data, d => d.value) ]);
      yAxis.transition().duration(1000).call(d3.axisLeft(y));

      // Create the u variable
      var u = svg.selectAll("rect")
        .data(data)

      u
        .join("rect") // Add a new rect for each new elements
        .transition()
        .duration(1000)
          .attr("x", d => x(d.group))
          .attr("y", d => y(d.value))
          .attr("width", x.bandwidth())
          .attr("height", d => height - y(d.value))
          .attr("fill", "#69b3a2")
          
      // Initialize the plot with the first dataset
      // update(data1)
    }
  }
}

I receive the following error messages:

Alpine Expression Error: myComponent is not defined

Expression: "myComponent()"
app.js:434 Uncaught ReferenceError: myComponent is not defined
    at eval (eval at safeAsyncFunction (app.js:478:14), <anonymous>:3:16)
    at app.js:496:21
    at tryCatch (app.js:423:12)
    at evaluate (app.js:441:32)
    at app.js:2621:15
    at Function.<anonymous> (app.js:1152:55)
    at flushHandlers (app.js:553:46)
    at stopDeferring (app.js:558:5)
    at deferHandlingDirectives (app.js:561:3)
    at initTree (app.js:764:3)

And when I click in any of the buttons the error is:

Alpine Expression Error: update is not defined

Expression: "update(data1)"

app.js:434 Uncaught ReferenceError: update is not defined
    at eval (eval at safeAsyncFunction (app.js:478:14), <anonymous>:3:16)
    at app.js:496:21
    at tryCatch (app.js:423:12)
    at app.js:2910:5
    at handler3 (app.js:2302:25)
    at app.js:2357:5
    at HTMLButtonElement.<anonymous> (app.js:2304:52)

Why does it work in the fiddle, but not in Laravel?

typeError: Cannot assign to read only property ‘tView’ of object ‘[object Object]’ in angular when redirect by login Url

I have two angular apps one is website and other one is load when we login.I have an issue when i goes to login component(in second app after login) with JWT Authentications it load splash screen in app.component.ts file and faced an error shows in screenshot attached with my question.After that i see splash screen long time instead of redirect to url.Please help me if you can.Thanks

enter image description here

Package.Json File  
 {
  "name": "metronic-angular",
  "version": "6.0.6",
  "description": "Packages used by Angular",
  "scripts": {
    "ng": "ng",
    "start": "echo hello && ng serve",
    "build": "ng build --configuration production",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "bundle-report": "webpack-bundle-analyzer dist/stats.json"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/schematics": "^12.2.14",
    "@angular/animations": "^12.2.14",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "^12.2.14",
    "@angular/compiler": "^12.2.14",
    "@angular/core": "^12.2.14",
    "@angular/forms": "^12.2.14",
    "@angular/platform-browser": "^12.2.14",
    "@angular/platform-browser-dynamic": "^12.2.14",
    "@angular/platform-server": "^12.2.14",
    "@angular/router": "^12.2.14",
    "@ckeditor/ckeditor5-angular": "^1.1.0",
    "@ckeditor/ckeditor5-build-classic": "^12.4.0",
    "@fortawesome/fontawesome-free": "^5.8.1",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@ng-bootstrap/ng-bootstrap": "^4.2.1",
    "@ngrx/effects": "^8.1.0",
    "@ngrx/entity": "^8.1.0",
    "@ngrx/router-store": "^8.1.0",
    "@ngrx/store": "^12.5.1",
    "@ngrx/store-devtools": "^8.1.0",
    "@ngx-loading-bar/core": "^4.2.0",
    "@ngx-translate/core": "^11.0.1",
    "@tinymce/tinymce-angular": "^3.3.1",
    "@types/lodash": "^4.14.136",
    "angular-in-memory-web-api": "^0.8.0",
    "bootstrap": "^4.3.1",
    "chart.js": "^2.8.0",
    "chartist": "^0.11.3",
    "classlist.js": "^1.1.20150312",
    "core-js": "^3.1.4",
    "google-libphonenumber": "^3.2.10",
    "highlight.js": "^9.15.8",
    "inputmask": "^5.0.3",
    "jquery": "^3.6.0",
    "lodash": "^4.17.11",
    "material-design-icons": "^3.0.1",
    "moment": "^2.18.1",
    "ng-inline-svg": "^8.5.1",
    "ngrx-store-freeze": "^0.2.4",
    "ngx-clipboard": "^12.2.0",
    "ngx-daterangepicker-material": "2.2.0",
    "ngx-highlightjs": "^3.0.3",
    "ngx-perfect-scrollbar": "^8.0.0",
    "ngx-permissions": "^7.0.3",
    "object-path": "^0.11.4",
    "perfect-scrollbar": "^1.4.0",
    "popper.js": "^1.15.0",
    "rxjs": "^6.5.3",
    "socicon": "^3.0.5",
    "tinymce": "^5.0.16",
    "tooltip.js": "^1.3.2",
    "tslib": "^2.0.0",
    "web-animations-js": "^2.3.2",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.14",
    "@angular/cli": "^12.2.16",
    "@angular/compiler-cli": "^12.2.14",
    "@angular/language-service": "^12.2.14",
    "@angular/material": "^12.2.13",
    "@angular/material-moment-adapter": "^12.2.13",
    "@ngrx/schematics": "^8.1.0",
    "@types/chai": "^4.3.0",
    "@types/chartist": "^0.9.46",
    "@types/highlight.js": "^9.12.3",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.6",
    "@types/jquery": "^3.5.10",
    "@types/node": "^12.11.1",
    "@types/object-path": "^0.11.0",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.9",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.2.0",
    "tslint": "~6.1.0",
    "typescript": "~4.3.5",
    "webpack-bundle-analyzer": "^3.3.2"
  }
}

App.Module

// Angular
import { BrowserModule } from '@angular/platform-browser';
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MAT_DATE_LOCALE } from '@angular/material/core';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { OverlayModule } from '@angular/cdk/overlay';
// Angular in memory
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
// Perfect Scroll bar
import { PERFECT_SCROLLBAR_CONFIG, PerfectScrollbarConfigInterface } from 'ngx-perfect-scrollbar';
// SVG inline
import { InlineSVGModule } from 'ng-inline-svg';
// Env
import { environment } from '../environments/environment';
// NGX Permissions
import { NgxPermissionsModule } from 'ngx-permissions';
// NGRX
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { StoreRouterConnectingModule } from '@ngrx/router-store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
// State
import { metaReducers, reducers } from './core/reducers';
// Copmponents
import { AppComponent } from './app.component';
// Modules
import { AppRoutingModule } from './app-routing.module';
import { CoreModule } from './core/core.module';
import { ThemeModule } from "./views/theme/theme.module";
// Partials
import { PartialsModule } from './views/partials/partials.module';
// Layout Services
import {
    DataTableService,
    FakeApiService,
    KtDialogService,
    LayoutConfigService,
    LayoutRefService,
    MenuAsideService,
    MenuConfigService,
    MenuHorizontalService,
    PageConfigService,
    SplashScreenService,
    SubheaderService
} from './core/_base/layout';
// Auth
import { AuthModule } from './views/pages/auth/auth.module';
import { AuthService } from './core/auth';
// CRUD
import { HttpUtilsService, LayoutUtilsService, TypesUtilsService } from './core/_base/crud';
// Config
import { LayoutConfig } from './core/_config/layout.config';
// Highlight JS
import { HIGHLIGHT_OPTIONS, HighlightLanguage } from 'ngx-highlightjs';
import * as typescript from 'highlight.js/lib/languages/typescript';
import * as scss from 'highlight.js/lib/languages/scss';
import * as xml from 'highlight.js/lib/languages/xml';
import * as json from 'highlight.js/lib/languages/json';

// tslint:disable-next-line:class-name
const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
    wheelSpeed: 0.5,
    swipeEasing: true,
    minScrollbarLength: 40,
    maxScrollbarLength: 300,
};

    StoreModule.forRoot(reducers,
        {
            metaReducers,
            //runtimeChecks: {
            //  strictStateImmutability: false,
            //  strictActionImmutability: false,
            //  strictStateSerializability: false,
            //  strictActionSerializability: false,
            //}
        }
    )
export function initializeLayoutConfig(appConfig: LayoutConfigService) {
    // initialize app by loading default demo layout config
    return () => {
        if (appConfig.getConfig() === null) {
            appConfig.loadConfigs(new LayoutConfig().configs);
        }
    };
}

export function hljsLanguages(): HighlightLanguage[] {
    return [
        { name: 'typescript', func: typescript },
        { name: 'scss', func: scss },
        { name: 'xml', func: xml },
        { name: 'json', func: json }
    ];
}

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserAnimationsModule,
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        environment.isMockEnabled ? HttpClientInMemoryWebApiModule.forRoot(FakeApiService, {
            passThruUnknownUrl: true,
            dataEncapsulation: false
        }) : [],
        NgxPermissionsModule.forRoot(),
        PartialsModule,
        CoreModule,
        OverlayModule,
        StoreModule.forRoot(reducers, { metaReducers }),
        EffectsModule.forRoot([]),
        StoreRouterConnectingModule.forRoot({ stateKey: 'router' }),
        StoreDevtoolsModule.instrument(),
        AuthModule.forRoot(),
        TranslateModule.forRoot(),
        MatProgressSpinnerModule,
        InlineSVGModule.forRoot(),
        ThemeModule
    ],
    exports: [],
    providers: [
        AuthService,
        LayoutConfigService,
        LayoutRefService,
        MenuConfigService,
        PageConfigService,
        KtDialogService,
        DataTableService,
        SplashScreenService,
        {
            provide: PERFECT_SCROLLBAR_CONFIG,
            useValue: DEFAULT_PERFECT_SCROLLBAR_CONFIG
        },
        {
            // layout config initializer
            provide: APP_INITIALIZER,
            useFactory: initializeLayoutConfig,
            deps: [LayoutConfigService], multi: true
        },
        {
            provide: HIGHLIGHT_OPTIONS,
            useValue: { languages: hljsLanguages }
        },
        // template services
        SubheaderService,
        MenuHorizontalService,
        MenuAsideService,
        HttpUtilsService,
        TypesUtilsService,
        LayoutUtilsService,
        { provide: MAT_DATE_LOCALE, useValue: 'en-GB' }
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

app.component.ts

import { Subscription } from 'rxjs';
// Angular
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
// Layout
import { LayoutConfigService, SplashScreenService, TranslationService } from './core/_base/layout';
// language list
import { locale as enLang } from './core/_config/i18n/en';
import { locale as chLang } from './core/_config/i18n/ch';
import { locale as esLang } from './core/_config/i18n/es';
import { locale as jpLang } from './core/_config/i18n/jp';
import { locale as deLang } from './core/_config/i18n/de';
import { locale as frLang } from './core/_config/i18n/fr';

@Component({
    // tslint:disable-next-line:component-selector
    selector: 'body[kt-root]',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit, OnDestroy {
    // Public properties
    title = 'Metronic';
    loader: boolean;
    private unsubscribe: Subscription[] = []; // Read more: => https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/

    /**
     * Component constructor
     *
     * @param translationService: TranslationService
     * @param router: Router
     * @param layoutConfigService: LayoutCongifService
     * @param splashScreenService: SplashScreenService
     */
    constructor(private translationService: TranslationService,
                private router: Router,
                private layoutConfigService: LayoutConfigService,
                private splashScreenService: SplashScreenService) {

        // register translations
        this.translationService.loadTranslations(enLang, chLang, esLang, jpLang, deLang, frLang);
    }

    /**
     * @ Lifecycle sequences => https://angular.io/guide/lifecycle-hooks
     */

    /**
     * On init
     */
    ngOnInit(): void {
        // enable/disable loader
        this.loader = this.layoutConfigService.getConfig('loader.enabled');
        console.log("LoaderStart");



        const routerSubscription = this.router.events.subscribe(event => {
            console.log(event);



            if (event instanceof NavigationEnd) {
                // hide splash screen
                this.splashScreenService.hide();
                console.log("True");
                // scroll to top on every route change
                window.scrollTo(0, 0);

                // to display back the body content
                setTimeout(() => {
                    document.body.classList.add('kt-page--loaded');
                }, 500);
            }
        });
        this.unsubscribe.push(routerSubscription);
    }

    /**
     * On Destroy
     */
    ngOnDestroy() {
        
        /*this.unsubscribe.forEach(sb => sb.unsubscribe());*/
    }
}

How to stop word ‘Array’ from rendering in table HTML?

How to stop the work ‘Array’ from being part of the output?? It appears between the headers and the data rows, and I can’t get rid of it. Is my HTML wrong for dynamic table rendering?? I would embed a picture but I’m not allowed yet to do that

UserID  First Name  Last Name   E-mail  Phone   Action
`Array`  
9   Lenny   Kravits [email protected] (234) 231-9999   
8   Sally   Simpson [email protected]    (425) 455-5678   
7   Chad    Merit   [email protected]   4251119988   
6   Janet   Miller  [email protected]  4251119988   
5   Tom Smith   [email protected] (425) 826-3344   
4   James   Miller  [email protected]  (425) 471-8101   
3   Ron Weasly  [email protected]   (111) 222-3344   
2   Harry   Potter  [email protected] (789) 654-135    
1   Sahil   Kumar   [email protected]    (078) 965-1235   

This is the getusers.php file that the Javasript calls as async/await/fetch.

<?php include_once 'init.php';
error_reporting(1);
$stmt = $pdo->prepare("CALL getUsers()");
$stmt->execute();
do {
$data = $stmt->fetchAll();
} while ($stmt->nextRowset() && $stmt->columnCount());
foreach ($data as $row) {
$data .= '  
<tr>
<td>' . $row['userId'] . '</td>
<td>' . $row['fName'] . '</td>
<td>' . $row['lName'] . '</td>
<td>' . $row['email'] . '</td>
<td>' . $row['phone'] . '</td>
<td>
<a href="#" id="' . $row['userId'] . '" class="btn btn-success btn-sm                   
rounded-pill py-0 editLink" data-bs-toggle="modal" data-bs- 
target="#editUserModal">Edit</a>
<a href="#" id="' . $row['userId'] . '" class="btn btn-danger btn-sm 
rounded-pill py-0 deleteLink">Delete</a>
</td>
</tr>        
';
}     
echo $data;      
?>

This is the user.php file with embedded Javascript in the same page (for now). This is the first time using the fetch api, with async/await. Everything renders, but the ‘array’ word appears as part of the ‘response’…and I’ve never had this issue before? For clarity I’m called a mysql stored procedure, very simple select * query…it works fine and the data renders.Using ‘document.querySelector(“table”)…maybe I have to dynamically render the whole table…which doesn’t yet work.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-icons.css" rel="stylesheet">                
<link href="css/fullcalendar.min.css" rel="stylesheet">
<title>Comments</title>
</head>
<body>
<div class="container">
<div class="row mt-4">
<div class="col-lg-12 d-flex justify-content-between align-items-center">
<div>
<h4 class="text-primary">All users in the database!</h4>
</div>
<div>
<button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs- 
target="#addNewUserModal">Add New User</button>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div id="showAlert"></div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="table table-striped table-bordered text-center">
<thead>
<tr>
<th>UserID</th>
<th>First Name</th>
<th>Last Name</th>
<th>E-mail</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!--Filled by AJAX-->
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
const tbody = document.querySelector("tbody");
// Fetch All Users Ajax Request
const fetchAllUsers = async () => {
const data = await fetch("includes/getusers.php", {
method: "GET",
});
const response = await data.text();
tbody.innerHTML = response;
console.log(response);
};
fetchAllUsers();
</script>
<script src="js/bootstrap.bundle.min.js"></script>
</body>
</html>

global variable not accessible in function

I have two global variables dateref and datetest that I call in two functions

the first function updates the value of dateref and datetest

In the second function i need to get the dateref and datetest values updated in the first function

here s what i tried doing in my code

my function:function(req,res){
        var dateref="";
        var datetest="";
 function firstfunction(){
            const jsonref= require ("..\..\..\json\"+req.body.ref);
            const jsontest= require ("..\..\..\json\"+req.body.test);
            this.dateref=date(jsonref);
            this.datetest=date(jsontest);
            //when i console.log dateref or jsontest here i get the updated value
            }
function secondfunction(){
           console.log(dateref)
           console.log(datetest)
           //here dateref and datetest are considered undefined
}

sum of two array in Node.js [duplicate]

I try to Sum below two Arrays and use below two Methods:


    A = [
                    25.8,                 27,
      24.099999999999998, 30.070000000000004,
                    34.3, 34.300000000000004,
                    34.3,                 33,
                    29.2,               29.2,
                    27.6, 28.999999999999996,
      29.310000000000002, 27.000000000000004
    ]
    
    B = [
      '0.00387000', '0.00472000',
      '0.00534000', '0.00460000',
      '0.00060000', '0.00032000',
      '0.00053000', '0.00327000',
      '0.00217000', '0.00217000',
      '0.00460000', '0.00415000',
      '0.00852000', '0.02241000'
    ]

Method 1


    //sum array function
    Array.prototype.SumArray = function (arr) {
        var sum = [];
        if (arr != null && this.length == arr.length) {
            for (var i = 0; i < arr.length; i++) {
                sum.push(this[i] + arr[i]);`enter code here`
            }
        }
        return sum;
    }
    
    C = A.SumArray(B);
    console.log (C)

Method 2


    var C = A.map(function (num, idx) {
      return num + B[idx];
    });

But the console result is the same as below:


    [
    '25.80.00387000',
    '270.00472000',
    '24.0999999999999980.00534000',
    '30.0700000000000040.00460000',
    '34.30.00060000',
    '34.3000000000000040.00032000',
    '34.30.00053000',
    '330.00327000',
    '29.20.00217000',
    '29.20.00217000',
    '27.60.00460000',
    '28.9999999999999960.00415000',
    '29.3100000000000020.00852000',
    '27.0000000000000040.02241000'
    ]

How can I add two array to make new Array like this:

[
‘25.80387000’,
‘27.00472000’,
.
.
.
.
.
.
]

Could anyone help to let me know why and how to fix this?

Nested firestore query in react

I have a firestore database with 2 collections: users and products. Users has a ‘cart’ field (type: array) which stores the uniqueName (field in products) of the products added to cart by a user. I fetched the ‘cart’ array and now, for each item, I want to fetch the product doc so I can access each product’s individual fields.
*currentUserCart stores the elements from the cart array: strings with the unique product name based on which I do the query in fetchProducts().

I tried this, but I get the correct products only if I click again wherever on the modal screen

 export const Navbarr = ({items}) => {
 

  const [user,  error] = useAuthState(auth);
  const [cartItems, setCartItems]=React.useState(0);
  const [open, setOpen] = React.useState(false);
  const [currentUserCart, setCurrentUserCart]=React.useState([]);
  const [currentProducts, setCurrentProducts]=React.useState([]);

  const handleOpen = () => {

    fetchUserCart();
    
    setOpen(true);
    fetchProducts();
    
    
  
  };

  const fetchProducts=async()=>{
    const products=[];
    currentUserCart.forEach(async(item)=>{
      const q = query(collection(db, "products"), where("uniqueName", "==", item));
      const doc = await getDocs(q);
      const data = doc.docs[0].data();
      setCurrentProducts(currentProducts=>[...currentProducts, data]);
    })

    
    console.log(currentProducts);
  }



  const fetchUserCart = async() =>{
    const q = query(collection(db, "users"), where("uid", "==", user?.uid));
      const doc = await getDocs(q);
      const data = doc.docs[0].data();  
      setCurrentUserCart(data.cart); 
      console.log('cart '+currentUserCart);
  }

  const handleClose = () => setOpen(false);
  const fetchUserCartItems=async()=>{
  
      const q = query(collection(db, "users"), where("uid", "==", user?.uid));
      const doc = await getDocs(q);
      const data = doc.docs[0].data();
      let cartItemsClone=data.cartItems;
      setCartItems(cartItemsClone);
     
  } 

  React.useEffect(() => {
    fetchUserCartItems();
    fetchUserCart();
    fetchProducts();
  }, [user], [currentUserCart], [currentProducts]);

Changing timer duration after onComplete event in React

Using react-countdown-circle-timer to render a countdown timer. Trying to create an event handler that changes the duration of the timer each time the timer reaches zero.

The clock initially runs down from 5 seconds, when it reaches zero I change the state, then use this to change the new value assigned to the clock.

For a more practical example. When the clock initially runs to zero, I change my stage state to 2, setting the timer to 6 seconds. When this clocks runs down, I change my stage state to 3, setting the timer to 7 seconds and so on, until I stop at stage 5

This is my code:

  const [ timer, setTimer ] = useState(5)
  const [stage, setStage] = useState(1)
  const timerMap = {
        2: 6,
        3: 7,
        4: 8,
        5: 9
    }
  const changeTimeHandler = (timer, setTimer) => {
        setStage(stage+1)
        setTimer(timerMap[stage])
        return { delay:1 }
  }
    console.log(timer)
  return (
    <div className="App">
      <div className="timer-wrapper">
        <CountdownCircleTimer
          isPlaying
          duration={timer}
          colors={["#004777", "#F7B801", "#A30000", "#A30000"]}
          colorsTime={[10, 6, 3, 0]}
          onComplete={() => (changeTimeHandler(timer, setTimer))}
          size={100}
        >
          {renderTime}
        </CountdownCircleTimer>
      </div>
    </div>
  );

When I run my code I get the error:

Warning: Received NaN for the 'strokeDashoffset' attribute. If this is expected, cast the value to a string.

Need help figuring out how to build the logic to get the desired effect.