For example:
import '___' from '___' or <script src="___.js"></script>?
But not things like async or deffer
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
For example:
import '___' from '___' or <script src="___.js"></script>?
But not things like async or deffer
I am using .net7.0 web app where js are added like bellow, I can use bar chart but I need gauge chart and when I am changing the type getting this error in the console, it says import { GaugeChart }, but in my approach how to do it, by the way just adding echarts.js in the plain html and it is working with my example but in my project not.
[ECharts] Series gauge is used but not imported.
import { GaugeChart } from 'echarts/charts';
echarts.use([GaugeChart]);
if (_runtimeState.Level == RuntimeLevel.Run)
{
_runtimeMinifier.CreateJsBundle("dependency-js-bundle",
bundlingOptions,
"~/lib/vue/vue.global.min.js",
"~/lib/axios/axios.min.js",
"~/lib/lodash.js/lodash.min.js",
"~/lib/echarts/echarts.js",
"~/lib/echarts/echarts.common.js",
"~/lib/echarts/echarts.simple.js",
"~/lib/simplebar/simplebar.min.js",
"~/lib/glightbox/js/glightbox.min.js"); // Other libraries
and I have a section where I am using vue js using Vue.createApp for each page like:
if (document.getElementById("comma-dashboard")) {
let dashboardFinder = Vue.createApp({
mounted() {this.init();},
methods: {
init() {
this.$nextTick(() => {
let attempts = 0;
let maxAttempts = 10; // Stop after 10 attempts (~2 sec)
let waitForMain = setInterval(() => {
let chartContainer = document.getElementById("main");
if (chartContainer) {
clearInterval(waitForMain); // Stop checking once found
var myChart = echarts.init(chartContainer);
var option = {
series: [
{
type: 'gauge',
center: ['50%', '60%'],
startAngle: 200,
endAngle: -20,
min: 0,
max: 60,
splitNumber: 12,
itemStyle: {
color: '#FFAB91'
},
progress: {
show: true,
width: 30
},
pointer: {
show: false
},
axisLine: {
lineStyle: {
width: 30
}
},
axisTick: {
distance: -45,
splitNumber: 5,
lineStyle: {
width: 2,
color: '#999'
}
},
splitLine: {
distance: -52,
length: 14,
lineStyle: {
width: 3,
color: '#999'
}
},
axisLabel: {
distance: -20,
color: '#999',
fontSize: 20
},
anchor: {
show: false
},
title: {
show: false
},
detail: {
valueAnimation: true,
width: '60%',
lineHeight: 40,
borderRadius: 8,
offsetCenter: [0, '-15%'],
fontSize: 60,
fontWeight: 'bolder',
formatter: '{value} L',
color: 'inherit'
},
data: [
{
value: 30
}
]
}
]
};
myChart.setOption(option, true);
} else {
console.warn(`Attempt ${attempts + 1}: #main not found`);
attempts++;
if (attempts >= maxAttempts) {
clearInterval(waitForMain);
console.error("Failed to find #main after multiple attempts.");
}
}
}, 1200); // Check every 200ms
});
}
}
});
dashboardFinder.mount('#comma-dashboard');
}
html looks like this
@{ Layout = "Master.cshtml";}
<div class="b2b-screens fix-screen-size" id="comma-dashboard">
<div id="main" style="width: 600px;height:400px;"></div>
</div
Like this working
I have encountered this unassignable error regarding the relaying props from one component to another component:
type ChildProps = { value: number } | { value: Array<number> };
const Child = ({ value }: ChildProps) => {
return <div>{`${value}`}</div>;
};
const Parent = ({ value }: ChildProps) => {
return <Child value={value} />; // TypeScript complains about this error here: `Type 'number' is not assignable to type 'number[]'.(2322)` (see below for the full error message)
};
const App = () => {
return (
<div>
<Parent value={10} />
</div>
);
};
You can also see this in StackBlitz here.
And here is the full error message I got:
Type '{ value: number | number[]; }' is not assignable to type 'IntrinsicAttributes & ChildProps'.
Type '{ value: number | number[]; }' is not assignable to type '{ value: number[]; }'.
Types of property 'value' are incompatible.
Type 'number | number[]' is not assignable to type 'number[]'.
Type 'number' is not assignable to type 'number[]'.(2322)
Is there any way to properly type the <Parent/> component in the following code snippet, so that we can fix the TypeScript error?
Unfortunately, the <Child/> component and thus the ChildProps are not owned by me and I cannot change them.
There is no error in console. I am confused with it. with the discord js version 14.18.0 I am using this from long time but never faced this error but now I am, Slash commands are not getting registered and its not showing any error. file path is also correct. I also deleted the node_modules and installed it again but didnt work at all.
const args = process.argv.slice(2);
const fs = require('fs')
const { PermissionsBitField, REST, Routes } = require('discord.js');
var colors = require('colors');
if(args.length > 0) {
require('dotenv').config()
}
const { TOKEN, CLIENT_ID } = process.env
//const { Routes } = require('discord-api-types/v10');
//const { REST } = require('@discordjs/rest');
const api = new REST({ version: '10' }).setToken(TOKEN)
async function getSlashCommands(client) {
let folder = fs.readdirSync('./commands/slash');
var slash_commands = [];
folder.forEach(dir => {
const commands = fs.readdirSync(`./commands/slash/${dir}`).filter(f => f.endsWith('.js') && !f.startsWith('-'))
for(var i in commands) {
var command = require(`../commands/slash/${dir}/${commands[i]}`)
if(command) {
if(client) client.slashCommands.set(command.name, command)
slash_commands.push(
{
name: command.name,
description: command.description,
type: command.type,
options: command.options || null,
default_permission: command.default_permission || null,
default_member_permission: command.default_member_permissions ? PermissionsBitField.resolve(command.default_member_permissions).toString() : null,
integration_types: command.integration_types || [0],
contexts: command.contexts || [0]
}
)
}
}
});
return slash_commands;
}
async function getApps(client) {
let appsFolder = fs.readdirSync('./apps/')
let appsList = []
appsFolder.forEach(dir => {
if(dir == 'modal') return
const apps = fs.readdirSync(`./apps/${dir}`).filter(f => f.endsWith('.js') && !f.startsWith('-'))
for(var i in apps) {
var app = require(`../apps/${dir}/${apps[i]}`)
if(app) {
if(client) client.slashCommands.set(app.name, app)
appsList.push(
{
name: app.name,
type: app.type,
default_permission: app.default_permission || null,
default_member_permission: app.default_member_permissions ? PermissionsBitField.resolve(app.default_member_permissions).toString() : null
}
)
}
}
});
return appsList;
}
async function registerCommands(client, dev = false) {
let slashCommands = await getSlashCommands(client)
let apps = await getApps(client)
let body = [...slashCommands, ...apps]
try {
if(dev) {
// await api.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.TEST_GUILD), { body })
await api.put(Routes.applicationCommands(CLIENT_ID), { body })
} else {
await api.put(Routes.applicationCommands(CLIENT_ID), { body })
}
console.log(`| Successfully Registered Slash Commands & Apps`.brightGreen)
} catch (error) {
console.log(error);
}
}
if(args[0] == 'sync') {
(async() => { await registerCommands(null, false); })()
} else {
(async() => { await registerCommands(null, (process.env.TEST_GUILD !== null)) })
}
// Put Commands to Discord API
module.exports = {
name: "slashCommands",
execute: async (client) => {
await registerCommands(client, (process.env.TEST_GUILD !== null))
}
}
I’m trying to upload a file using the Qontak API based on the documentation provided here:
https://github.com/mekari-engineering/qontak-api-js/blob/main/src/resources/file_uploader.ts
However, the request always fails and returns an HTML error related to Incapsula (Imperva), as shown below:
request line POST /qontak/chat/v1/file_uploader HTTP/1.1
Error: <html style="height:100%"><head><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><meta name="format-detection" content="telephone=no"><meta name="viewport" content="initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></head><body style="margin:0px;height:100%"><iframe id="main-iframe" src="/_Incapsula_Resource?CWUDNSAI=23&xinfo=14-18748584-0%20NNNY%20RT%281743153273568%20373%29%20q%280%200%200%20-1%29%20r%281%20-1%29%20B15%281%2c501%2c51%29%20U24&incident_id=1767000280150547423-101893486418528014&edet=15&cinfo=01000000ee8e&rpinfo=0&mth=POST" frameborder=0 width="100%" height="100%" marginheight="0px" marginwidth="0px">Request unsuccessful. Incapsula incident ID: 1767000280150547423-101893486418528014</iframe></body></html>
Here’s the code I’m using:
async function uploadMedia() {
try {
const filePath = './cta-url.png';
if (!fs.existsSync(filePath)) {
throw new Error(`File not found at path: ${filePath}`);
}
const fileBuffer = fs.readFileSync(filePath);
const response = await api.file_uploader.uploadFile({file: fileBuffer});
console.log("Upload Response:", response);
} catch (error) {
console.error("Error:", error.response?.data || error.message);
}
}
uploadMedia();
I’m not sure why the request is being intercepted or blocked by Incapsula. How do I resolve this Incapsula block?
Any help would be greatly appreciated!
I’m new to D3.js but also to JavaScript in general so this might be easy for you to answer. I’m using the D3.js “data join” pattern to display an array of 200 numbers as a curve. I came up with the following code:
this.svg
.selectAll('line')
.data(this.buffer)
.join('line')
.attr('x1', function (d, i) {return 5 * i})
.attr('x2', function (d, i)
{
if (i < 199)
return 5 * (i + 1)
else
return 5 * i
})
.attr('y1', function (d, i) {return d})
.attr('y2', function (d, i)
{
if (i < 199)
return this.buffer[i+1]
else
return d
})
.attr('style', 'stroke:black;stroke-width:1')
The data is in the “buffer” variable. Initially, I got this to work in a simple script where this code was a function and “buffer” was a global variable (and therefore in the scope of everything else). Eventually I decided to encapsulate it in a class, and thus “buffer” became “this.buffer”.
Unfortunately, “this” is not in the scope of the anonymous functions, and so I get an error when I try to use it to get the value of the next element in “this.buffer”:
Uncaught TypeError: Cannot read properties of undefined (reading ‘1’)
Maybe there’s a much simpler way to plot those points, but the D3.js documentation is a nightmare to search through and I didn’t find anything. That’s why I’m basically drawing lines by taking each value in my array and the value that follows.
It would be great if those accessor functions could have access to the array I passed to the “data” function. I suppose there has to be a reference somewhere for D3.js to generate those calls to the anonymous functions. Maybe I just don’t know the “trick”. Can you point me in the right direction ? I’m open to scrapping this entire piece of code if it turns out I just didn’t have the correct mindset.
I am trying to access my header variables sent from NodeJS in my script.js file.
I can successfully pass the variables into my EJS templates and use them there; however, I can find a way to access the passed variables in a link script.js file.
I am passing the variables from NodeJS like this:
res.render(“home”, {ACTIVE_TASKS: active_tasks, COMP_TASKS: comp_tasks, TODAY:today})
There’s no problem activing ACTIVE_TASKS in the EJS document using <%= %>, but I can’t access the headers in my script.js file.
Are there any good suggestions for passing the header variables into the script file directly?
<div class = "ad-container"></div>
<script>
let html = '';
function createAd() {
const adBoxElement = document.querySelector('.ad-box');
const closeButtonElement = document.querySelector('.close-button');
const adContainerElement = document.querySelector('.ad-container');
let localHtml =
`
<div class="ad-box">
<div class="close-button">X</div>
<div class="ad-text">Google Ads</div>
</div>
`;
html += localHtml;
adContainerElement.innerHTML = html;
closeButtonElement.addEventListener('click', () => adBoxElement.remove());
}
setTimeout(createAd, 2000);
</script>
hi i’m new to javaScript, i want to create something like an ad that apears after 2 sceonds , and then remove it by clicking on X button .it Work’s when i call a function to create the ad .but why it dosen’t Work with setTimeOut() ???
Can somebody explain me why this:
[js fiddle fig1][1]
is working and the same code put in codepen does not:
[js fiddle fig2][2]
[1]: https://jsfiddle.net/29pesoL5/
[2]: https://codepen.io/pt001/pen/emYPREK
I have the problem to get code 1 working in my project. I already added the magicscroll.io library to my project and it did not work.
There is a working example of a javascript script that loads content when scrolling. Everything works, but inside foreach, modal windows don’t open and scripts don’t work at all. I would really appreciate your help.
<script>
const citiesContainer = document.getElementById('cities');
const btnLoad = document.getElementById('load');
const loader = document.querySelector('.loader');
let page = 1;
let lock = false;
async function getCities() {
const res = await fetch(`index.php?page=${page}`);
return res.text();
}
// getCities();
async function showCities() {
const cities = await getCities();
if (cities) {
citiesContainer.insertAdjacentHTML('beforeend', cities);
lock = false;
} else {
btnLoad.classList.add('d-none');
lock = true;
}
}
loader.classList.add('show');
setTimeout(() => {
showCities();
loader.classList.remove('show');
}, 1000);
btnLoad.addEventListener('click', () => {
loader.classList.add('show');
setTimeout(() => {
page++;
showCities();
loader.classList.remove('show');
}, 1000);
});
window.addEventListener('scroll2', () => {
const {scrollTop, scrollHeight, clientHeight} = document.documentElement;
// console.log(scrollTop, scrollHeight, clientHeight);
if (scrollTop + clientHeight >= scrollHeight) {
if (false === lock) {
lock = true;
loader.classList.add('show');
setTimeout(() => {
page++;
showCities();
loader.classList.remove('show');
}, 1000);
}
}
});
// МОДАЛЬНОЕ ОКНО //
document.addEventListener('DOMContentLoaded', () => {
const mOpen = document.querySelectorAll('[data-modal]');
if (mOpen.length == 0) return; // если нет элементов управления всплывающими окнами, прекращаем работу скрипта
const overlay = document.querySelector('.modal__overlay'),
modals = document.querySelectorAll('.modal__body'),
mClose = document.querySelectorAll('[data-close]');
for (let el of mOpen) {
el.addEventListener('click', modalShow); // регистрируются обработчик события открытия модального окна
}
for (let el of mClose) {
el.addEventListener('click', modalClose); // регистрируются обработчик события нажатия на крестик
}
document.addEventListener('keydown', modalClose); // регистрируются обработчик события нажатия на клавишу
function modalShow(modal) {
let modalId = this.dataset.modal;
document.getElementById(modalId).classList.add('open');
overlay.classList.add('open');
}
function modalClose(event) {
if ( event.type != 'keydown' || event.keyCode === 27 ) {
for (let modal of modals) {
modal.classList.remove('open');
overlay.classList.remove('open');
}
}
}
})
// -- //
</script>
<style>
.loader {display: none;}
.loader img {width: 100px;}
.show {display: block;}
.modal__body {
position: fixed; top: 0; left: 50%; margin: 8px 0; max-height: 95%; width: 95%; max-width: 500px;
opacity: 0; visibility: hidden; z-index: 5; background: #F4F5F5;
-webkit-transition: 0.3s all; -moz-transition: 0.3s all; -o-transition: 0.3s all; -ms-transition: 0.3s all; transition: 0.3s all;
-webkit-transform: translate(-50%, -100%); -moz-transform: translate(-50%, -100%); -ms-transform: translate(-50%, -100%); transform: translate(-50%, -100%);
}
</style>
<?php
function get_start(int $page, int $per_page): int {
return ($page - 1) * $per_page;
}
function get_cities(int $start, int $per_page): array {
global $db;
$stmt = $db->prepare("SELECT * FROM city LIMIT $start, $per_page");
$stmt->execute();
return $stmt->fetchAll();
}
if (isset($_GET['page'])) {
$page = (int)$_GET['page'];
$per_page = 200;
$start = get_start($page, $per_page);
$cities = get_cities($start, $per_page);
$html = '';
if ($cities) {
foreach ($cities as $city) {
$html .= "
<li>
{$city['name']}: {$city['population']}
<a href='javascript:void(0)' data-modal='com-delete_{$city['id']}'>Удалить</a>
</li>
<!-- Модальное окно -->
<div class='modal__body' id='com-delete_{$city['id']}'>
<div class='modal__content'>
<a href='/comments/control/action/delete/id/565' class='button'>Удалить</a>
<a href='javascript:void(0)' class='button' data-close=''>Отмена</a>
</div>
</div>";
}
}
echo $html;
die;
}
?>
<ul id="cities"></ul>
<div class="loader">
<img src="ripple.svg" alt="">
</div>
<button class="btn btn-primary" id="load">Load more</button>
<footer style="background-color: #000; height: 200px; padding: 0;"></footer>
There is a working example of a javascript script that loads content when scrolling. Everything works, but inside foreach, modal windows don’t open and scripts don’t work at all. I would really appreciate your help.
I came across a usecase where I need to mask the values inside the draft-js-plugins-editor and have a toggle button to mask and unmask values similar to input type password.
The masking needs to be conditional. So if a user starts typing with ‘{‘ we do not need to mask but if he types in any other plain text , we need to mask it.
How can I implement this in the draft-js-plugins-editor?
I am creating a Sentinel-2 median composite in Google Earth Engine using the following scripts:
How to achieve a more natural-looking and sharper Cloudless Sentinel-2 composite in GEE?
I am generating Sentinel-2 composites in Google Earth Engine using either of the following scripts:
Script A:
// STEP 1: Define ROI & Season
var roi = ee.Geometry.Rectangle([76.84, 28.40, 77.35, 28.88]);
var startDate = '2023-06-01';
var endDate = '2024-08-31';
// STEP 2: Load and Filter Sentinel-2
var s2 = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(roi)
.filterDate(startDate, endDate)
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
.select(['B4', 'B3', 'B2', 'SCL']);
// STEP 3: Cloud/Shadow Mask
function maskClouds(image) {
var scl = image.select('SCL');
var cloudShadow = scl.eq(3);
var cloudsMed = scl.eq(8);
var cloudsHigh = scl.eq(9);
var cirrus = scl.eq(10);
var mask = cloudShadow.or(cloudsMed).or(cloudsHigh).or(cirrus);
return image.updateMask(mask.not());
}
var composite = s2.map(maskClouds).median();
// STEP 4: Visualization
Map.centerObject(roi, 10);
Map.addLayer(composite, {
bands: ['B4','B3','B2'],
min: 0,
max: 3000,
gamma: 1.2
}, 'Cloud-Free Sentinel-2');
// STEP 5: Export
Export.image.toDrive({
image: composite,
description: 'Sentinel2_India_Delhi_Improved',
folder: 'Sentinel2_Exports',
scale: 10,
region: roi,
fileFormat: 'GeoTIFF',
maxPixels: 1e13
});
Script B:
// STEP 1: Define ROI & Season
var roi = ee.Geometry.Rectangle([76.84, 28.40, 77.35, 28.88]);
var startDate = '2023-06-01';
var endDate = '2024-08-31';
// STEP 2: Load and Filter Sentinel-2
var s2 = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(roi)
.filterDate(startDate, endDate)
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
.select(['B4', 'B3', 'B2', 'SCL']);
// STEP 3: Simple Cloud Mask
function maskClouds(image) {
var cloudProb = image.select('SCL').eq(9);
return image.updateMask(cloudProb.not());
}
var composite = s2.map(maskClouds).median();
// STEP 4: Visualization
Map.centerObject(roi, 10);
Map.addLayer(composite, {
min: 500,
max: 7000,
bands: ['B4', 'B3', 'B2']
}, 'Cloud-Free Sentinel-2');
// STEP 5: Export
Export.image.toDrive({
image: composite,
description: 'Sentinel2_India_Delhi500_700',
folder: 'Sentinel2_Exports',
scale: 10,
region: roi,
fileFormat: 'GeoTIFF',
maxPixels: 1e13
});
In both scripts, the composite always looks too saturated, unnatural, or not sharp. I’ve tried adjusting the min, max, and gamma values, but it still comes out oversaturated or lacking natural color. How can I better scale or stretch the pixel values (or otherwise process the composite) so it appears more true-to-life in Google Earth Engine? A nice looking satellite photo?
Field on the right should be green
Thanks!!
Earn Money & Grow Your Career with Microjobwork.com!
Are you looking for a flexible way to earn money online? Do you want to showcase your skills and get paid for small, easy tasks? Microjobwork.com is the perfect platform for you!
Why Join Microjobwork.com?
✅ Work from Anywhere – Complete tasks from the comfort of your home and earn money.
✅ Flexible Hours – No fixed schedule! Work when you want, as much as you want.
✅ Diverse Job Categories – Find a wide range of jobs, including:
Data entry
Graphic design
Social media promotion
Writing & translation
Website testing
Many more!
✅ Fast & Secure Payments – Get paid securely and quickly for your work.
✅ Easy to Get Started – No experience needed! Just sign up, browse tasks, and start earning.
How It Works?
So I’ve found myself needing to make grids of different things for visualizations and the work flow for me has usually been:
And because I have found myself doing this so often, I wanted to make a function where I can pass the smaller, single-vis function to and let it draw the grid of elements. Let’s call it drawInGrid()
There seemed to be two obvious ways for me to do this: either have the this drawInGrid() function draw a bunch of svg and store them in array as they’re returned and then draw the grid, OR modify each individual element drawing function to accept as ‘base’ svg as an argument, draw to it and move on. I opted for the second option and now I’m wondering if there is a general best practice for doing this?
The current set up I have is drawInGrid(fn, dimens, arr), where the fn is the smaller, individual function, dimens is an object giving the number of elements in a column and row, and how big each element should be, plus some padding info, and arr is an array of the data that will be passed on to fn for each grid element as it’s drawn. This function arranges a bunch of tags and then gives those to the fn function. As a result of this set up, the fn function must be structured a certain way. It must accept a base d3 object to append to, values of data to use in the drawing and dimension for how much space it has in the grid to draw the section.
Does this seem like a good way of going about this? Am I missing something obvious? Any input on how to think about doing this efficiently would be greatly appreciated 🙂
function drawInGrid(fn, dimens, arr) {
// elem_w = ?
// elem_h = ?
// padding = 0
// grid_h = ?
// grid_w = ?
// height = overwrite
// width = overwrite
// either 2 of 3 must be specified: elem_*, grid_*, height, width
const padding = dimens.padding
const elem_w = dimens.elem_w + dimens.padding
const elem_h = dimens.elem_h + dimens.padding
const grid_w = dimens.grid_w
const grid_h = dimens.grid_h
if (typeof elem_w === 'undefined') {
throw new Error("elem_w is not defined!");
}
if (typeof elem_h === 'undefined') {
throw new Error("elem_h is not defined!");
}
if (typeof padding === 'undefined') {
throw new Error("padding is not defined!");
}
if (typeof grid_w === 'undefined') {
throw new Error("grid_w is not defined!");
}
if (typeof grid_h === 'undefined') {
throw new Error("grid_h is not defined!");
}
const height = padding + (elem_h * grid_h)
const width = padding + (elem_w * grid_w)
// create the base svg upon which everything will be built
var svg = d3.create('svg')
.attr('height', height)
.attr('width', width)
// basic background rect for entire figure
var bkgrd = svg.append('rect')
.attr('height', height)
.attr('width', width)
.attr('fill', 'white')
.attr('stroke', 'black')
.attr('stroke-width', '3px')
// grouping for all the grid elements we're going to draw and moving it down and right by 'padding'
var grid = svg.append('g')
.attr('class', 'grid')
.attr('transform', `translate(${padding}, ${padding})`)
/*
height, width, and padding are all already set.
the number of grid elems in the grid is also defined below
the entire grouping of all grid elems is shifted 1 padding value right and down already.
each grid elem also has 1 padding value subtracted in from the right and lower bound when drawing the dotted rectangle
*/
const rackHeight = ((height - padding) / grid_h)
const rackWidth = ((width - padding) / grid_w)
// ^^ 3/15/25: for now im just forcing the user to define these as grid_h and grid_w
// usable elem arr includes null markers for racks that should exist in the freezer, but are not present in the data
const usableElemArr = arr.slice(0, grid_h*grid_w).concat(
Array(
d3.max([(grid_w*grid_h) - arr.length, 0])
).
fill({rack: "Empty", count: 0})
)
console.log('usable rack counts: ' + usableElemArr.lenght)
console.log(usableElemArr)
var vDimens = dimens // an updated dimens that is only for the eyes of the child elem drawing function
vDimens.elem_h = dimens.elem_h
vDimens.elem_w = dimens.elem_w
grid
.selectAll('g')
.data(usableElemArr)
.join('g')
.attr('transform', (d, i) => 'translate(' + (rackWidth * (i % grid_w)) +',' + (Math.floor(i / grid_w)) * rackHeight + ')')
.each(function(d) {
fn(d3.select(this), d, vDimens)
})
return svg
}
function fillElem(base, val, dimens) {
base
.append('rect')
.attr('height', dimens.elem_h)
.attr('width', dimens.elem_w)
// .attr('fill', val)
.attr('id', 'elem')
.attr('fill', 'white')
.attr('stroke', 'red')
.attr('stroke-width', '2px')
.attr('stroke-dasharray', '4 1')
}
I need to insert multiple rows that pulling from some forms (crud application). One header data into a header table and a detail table. here is the ss of the form :
https://paste.pics/T2PBO
The header data id will be used when insert multiple rows data to the detail table.
I am using one-to-many from this link as reference:
https://www.myphptutorials.com/tutorials/print-154
but I got error when save the data : “Notice: Undefined offset: 1 in C:xampp5htdocstriplespagination.php on line 104
all rows
etc..
// header
$resultExec1 = mysqli_query($db, "insert into header " .
"(user_id,
buyer,
test1,
trxid,
total
) " .
"VALUES ('" . $_SESSION['id'] . "', " .
"'" . $_POST['buyer'] . "', " .
"'" . $_POST['test1'] . "', " .
"'" . $_POST['trxid'] . "', " .
"'" . $_POST['total1'] . "')");
$query1 = mysqli_query($db, "SELECT max(Alt_Id) AS id_header FROM detail limit 1");
$data = mysqli_fetch_array($query1);
$id_agens = $data['id_header'];
foreach($_POST['country1'] as $key => $ctry){
$country1 = $ctry;
$resultExec2 = mysqli_query($db,
"insert into detail " .
"(user_id,
test1,
id_header,
test2,
test21,
test22,
test3,
test31,
test32,
test4,
test41,
test42) " .
"VALUES ('" . $_SESSION['id'] . "', " .
"'" . $ctry . "', " .
"'" . $id_header. "', " .
"'" . $_POST['test2'][$key] . "', " .
"'" . $_POST['test21'][$key] . "', " .
"'" . $_POST['test22'][$key] . "', " .
"'" . $_POST['test3'][$key] . "', " .
"'" . $_POST['test31'][$key] . "', " .
"'" . $_POST['test32'][$key] . "', " .
"'" . $_POST['test4'][$key] . "', " .
"'" . $_POST['test41'][$key] . "', " .
"'" . $_POST['test42'][$key] . "')");}
can someone please explain with an example how to construct a query to insert multiple line items and the appropriate query without error undefined index? Thank you so much.