print multiple copies in php using window.print

I am trying to print multiple copies of just a product name on a sticker. No of copies would be passed by popup onto print.php page.
I tried using while loop to use window.print but it prints only 1 copy.
heres my code:

function PrintPage() {
     var count = <?echo $prnt?>;
while (count >0){
       // alert("print");
    window.print();
    count--;
    
}
 window.close();

}
document.loaded = function(){
    
}
window.addEventListener('DOMContentLoaded', (event) => {
    PrintPage()
    setTimeout(function(){ window.close() },750)
});

used alert to debug if loops works, its showing.
I know this is regularly asked question ,however, I tried and its not working for me. Please help

React framer-motion – how to start counting scrollYProgress starting from specific div

What I want to do is to count the scrollYProgress when the viewport arrives the top of the container and scrollYProgress should be 1 when leaving the box. How can I do it?

The current problem is that scrollYProgress start counting at the top of the application.

enter image description here

App.js

import React, { useState, useEffect } from "react";
import "./styles.css";
import { motion, useViewportScroll } from "framer-motion";

export default function App() {
  const { scrollYProgress } = useViewportScroll();

  useEffect(() => {
    return scrollYProgress.onChange((v) => {
      console.log(v);
    });
  }, [scrollYProgress]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <motion.div>
        <div
          style={{ height: "500px", margin: "1rem", border: "1px solid grey" }}
        >
          How to start Counting the percentage from 0 here
        </div>
      </motion.div>
      <h2>The percentage will be 100% when arriving the end of the box</h2>
    </div>
  );
}

Codesandbox
https://codesandbox.io/s/adoring-poincare-curjo?file=/src/App.js:177-192

As I import BrowserRouter from ‘react-router-dom’ my app stops working. I have attached the error. The error in index.js file but I haven’t touched i

×
TypeError: Object(…) is not a function
./node_modules/react-router/index.js
C:/devansh/React/routing-on-http–01-starting-setup/http–05-finished/node_modules/react-router/index.js:56
53 | */
54 |
55 |

56 | const NavigationContext = /#PURE/createContext(null);
57 |
58 | if (process.env.NODE_ENV !== “production”) {
59 | NavigationContext.displayName = “Navigation”;
View compiled

Descending order is not working in Datatable when coming from database

From the database I am fetching the value :-

Array
(
    [0] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2022-01-10
            [candidate_name] => sathish sat
        )

    [1] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2022-01-10
            [candidate_name] => sathish sat
        )

    [2] => stdClass Object
        (
            [company_email] => [email protected], [email protected]
            [schedule_date] => 2022-01-05
            [candidate_name] => sathish sat
        )

    [3] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Sai Surendra Datar
        )

    [4] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Rahul Raj
        )

    [5] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Dilpreet kaur
        )

    [6] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Sai Surendra Datar
        )

    [7] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Rahul Raj
        )

    [8] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Rahul Raj
        )

    [9] => stdClass Object
        (
            [company_email] => [email protected], [email protected]
            [schedule_date] => 2021-12-18
            [candidate_name] => Sai Surendra Datar
        )

    [10] => stdClass Object
        (
            [company_email] => [email protected], [email protected]
            [schedule_date] => 2021-12-18
            [candidate_name] => sathish sat
        )

    [11] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-18
            [candidate_name] => sathish sat
        )

)

But when showing in the datatable order are missmatching refer the image URL I have mentioned
Display of the datatable
URl – https://i.stack.imgur.com/FJLgg.png
enter image description here

This is my code:-

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap4.min.js"></script>
<table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Candidate Name</th>
                <th>Company Email</th>
                <th>Schedule Date</th>
            </tr>
        </thead>
        <tbody>
            <?php $x = 1; foreach ($candidate_list as $record) { ?>
                            <tr> 
                                <td style="text-align: left;color: #5e5e5e;"><?php echo $record->candidate_name; ?></td>
                                <td style="text-align: left;color: #5e5e5e;"><?php echo $record->company_email; ?></td> 
                                <td class="sorting sorting_asc sorting_1" style="text-align: left;color: #5e5e5e;"><?php echo date('d-m-Y', strtotime($record->schedule_date)); ?></td>
                                </td>
                            </tr>
                        <?php $x++;} ?>
        </tbody>
       
    </table>
    <script type="text/javascript">
        $(document).ready(function() {
    $('#example').DataTable();
} );
    </script>

Kindly give me the solution. I need the order as from the database. How to solve this?

ReactJS Prop returning default value in some functions

I have a ReactJS file where at the top I have one of my props defined as

const [items, setItems] = useState(0);

This updates a value I show on the screen properly, and when I read the value of items in some functions, I do get the proper value of items. However, on one specific function with the prototype of const updateCart = (client) => {}, when I try to get the value of items, I get the default value defined in the useState(0);. I do understand that props do not always update instantly, but even after reading the value correctly in another function, when I try to read it in the updateCart() function I always get the default value, not the current value. How can I read the current value in my updateCart() function?

Thank you

Form submit button in a DataTable not working as subarray

Hello i am using a datatable to retrive data with dynamic table data. using subarray to fetch data . i have included a form to that aray but the form function is not working whene i script to the fetch file. please help me with this.

    <?php
session_start();
// $id = $_SESSION['id'];
//fetch.php
$connect = mysqli_connect('localhost', 'sbcldb_management', 'management_server2021', 'sbcldb_management');
$columns = array('C_Number', 'coupon', 'date', 'District','Upazilla','storename','eye');
$query = "SELECT * FROM code_genarate WHERE status='1' ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'AND
  (C_Number LIKE "%'.$_POST["search"]["value"].'%"
  OR coupon LIKE "%'.$_POST["search"]["value"].'%"
  OR date LIKE "%'.$_POST["search"]["value"].'%"
  OR District LIKE "%'.$_POST["search"]["value"].'%"
  OR Upazilla LIKE "%'.$_POST["search"]["value"].'%"
  OR storename LIKE "%'.$_POST["search"]["value"].'%")
  ';
}

if($_POST["district"] != '')
{
$did = $_POST["district"];
$sql = "SELECT * FROM districts WHERE id = '$did'";
$res = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($res))
{
  $district = $row['district'];
}
$uid = $_POST["upazilla"];
if($uid > 0){
  $sql = "SELECT * FROM upazilla WHERE id = '$uid'";
  $res = mysqli_query($connect, $sql);
  while($row = mysqli_fetch_array($res))
  {
    $upazilla = $row['upazilla'];
  }
 $query .= "AND District='$district' AND Upazilla= '$upazilla'";
 }else{

 $query .= "AND District='$district'";
 }

$query1 = '';

if($_POST["length"] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));

$result = mysqli_query($connect, $query . $query1);

$data = array();
// $total = 0;
while($row = mysqli_fetch_array($result))
{
  // $total += $row["Amount"];
  $sub_array = array();
  // $sub_array[] = '<a href="../customers/customerdetails.php?id='.$row['C_Number'].'">'.$row['C_Number'].'</a>';
  // $sub_array[] = $row["Amount"];;
  // $sub_array[] = $row["SaleDate"];
  $sub_array[] = $row["C_Number"];
  $sub_array[] = $row["coupon"];
  $number = $row['C_Number'];

  $sub_array[] = $row["date"];
  $sub_array[] = $row["District"];
  $sub_array[] = $row["Upazilla"];
  $sub_array[] = $row["storename"];

  $sub_array[] = '<form name="submit-to-gateway" id="myForm">
  <div id="form_alerts"></div>
  <div class="row">
    <div class="col-8">
  <input type="hidden" name="text" value="Dear Retailer, Your Software Download link is http://sbcldb.ltd/application/sbcldb.apk  ,With the best Regards, SBCLDB LIMITED." </input>
  <input type="text" class="form-control" name="number" value="'.$row['C_Number'].'"/>
  </div>
  <div class="col-4">
  <button class="btn btn-primary" type="submit" class="form-control" id="sms_btn" name="sms_btn">Send</button>

</div>
</div>
  </form>';
  $data[] = $sub_array;
}
function get_all_data($connect)
{
$quer = "SELECT * FROM retailer_sales";
 $result = mysqli_query($connect, $quer);
 return mysqli_num_rows($result);
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  get_all_data($connect),
 "recordsFiltered" => $number_filter_row,
 "data"    => $data
);




echo json_encode($output);



<script>
  const scriptURL = 'https://script.google.com/macros/s/AKfycbzfMQmBwDEO8k0H8jeLlKTE_GzK0XuQ1unZd_5ib_DDBhM17b6FVahIW5f3W4FyfCNOAw/exec'
  const form = document.forms['submit-to-gateway']

  form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, {
        method: 'POST',
        body: new FormData(form)
      })
      .then(response => $("#form_alerts").html("<div class='alert alert-success'>Id Sent Successfully.</div>"))
      .catch(error => $("#form_alerts").html("<div class='alert alert-danger'>Id Could not be Sent.</div>"))
      $('#myForm')[0].reset();
  })
</script>


?>

the form is submitting on a html page perfectly but i cant merger this to the datatable.
please help me with this.

Set value in object at dynamic key, possibly further than first given scope

I have 2 user-provided strings acting as a key, and a value. Let’s say, for example, "foo" and "Hello World!". I have an object that I want to modify, and set obj.foo to Hello World!.

The problem is that the key can lead to an indefinitely nested object. For example, I should be able to use the key foo.bar[baz].qux or any strange JS-syntax sequence like that to set a value inside a nested object, or declare one if necessary.

Furthermore, I’m gonna have to access these values with another user-provided string that could be in a different format (for example, foo[bar][baz][qux] instead). Is there a way to do all of this without using eval()?

Before someone marks it, this question isn’t a duplicate of change structure of an object javascript because

  1. That question does not address the last part of this one,
  2. It’s 7 years old, and interacting with objects has become a lot easier over updates (maybe my question would be easier to answer with recent versions?) and
  3. It also doesn’t address using [] (not as big of a problem, until you have people using both types in one long expression)

React JS: Unexpected token < in JSON at position 0

I’m trying to parse and get fetch data from URL, but got the error like:

Unexpected token < in JSON at position 0

the URL contains this such of data:

<wfs:FeatureCollection xmlns="http://www.opengis.net/wfs" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:kict="kict" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://192.168.0.70:28080/geoserver/schemas/wfs/1.0.0/WFS-basic.xsd kict http://192.168.0.70:28080/geoserver/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=kict%3Av_plans_photo">
<gml:boundedBy>
<gml:null>unknown</gml:null>
</gml:boundedBy>
<gml:featureMember>
<kict:v_plans_photo fid="v_plans_photo.fid-400b9b06_17e425c6260_-1a99">
<kict:rownum>61689</kict:rownum>
<kict:plan_id>6178a7a0974e58001ac90ac5</kict:plan_id>
<kict:cmo>5c38212c23b65b0d045d2de8</kict:cmo>
<kict:cmo_str>5c38212c23b65b0d045d2de8</kict:cmo_str>
<kict:plan_name/>
<kict:plan_cn>포트홀 작업추가</kict:plan_cn>
<kict:opert_ty>B1</kict:opert_ty>
<kict:operTy>B1</kict:operTy>
<kict:opert_sttus>A4</kict:opert_sttus>
<kict:opert_plan_cn>포트홀 작업추가</kict:opert_plan_cn>
<kict:create_at_year>2021</kict:create_at_year>
<kict:create_at_month>10</kict:create_at_month>
<kict:create_at_week>43.0</kict:create_at_week>
<kict:created_at>2021-10-27T01:13:04.557Z</kict:created_at>
<kict:created_by>강릉_보수원002</kict:created_by>
<kict:cvpl_ty>5cfda3bab615b60845c79dda</kict:cvpl_ty>
<kict:acmslts_id>6178a89e974e58001ac90b02</kict:acmslts_id>
<kict:cvpl_ty_code>900900</kict:cvpl_ty_code>
<kict:cvpl_ty_nm>포트홀</kict:cvpl_ty_nm>
<kict:cvpl_name>포트홀</kict:cvpl_name>
<kict:cmo_org_code>1613208</kict:cmo_org_code>
<kict:cmo_grp_nm>원주청</kict:cmo_grp_nm>
<kict:cmo_code>22</kict:cmo_code>
<kict:cmo_nm>강릉국토관리사무소</kict:cmo_nm>
<kict:cmoNm>강릉국토관리사무소</kict:cmoNm>
<kict:photo_type>완료</kict:photo_type>
<kict:begin_lat>37.7164584026444</kict:begin_lat>
<kict:begin_lon>128.987696737366</kict:begin_lon>
<kict:photo_lat>37.7161098</kict:photo_lat>
<kict:photo_lon>128.9880585</kict:photo_lon>
<kict:geom>
<gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">128.9880585,37.7161098</gml:coordinates>
</gml:Point>
</kict:geom>
<kict:photo_url>http://hms.molit.go.kr:9080/api/uploads/2021/6178a7a0974e58001ac90ac5_202110271017147661635297434478.png</kict:photo_url>
<kict:store_path>uploads/2021/6178a7a0974e58001ac90ac5_202110271017147661635297434478.png</kict:store_path>
<kict:photo_filename>6178a7a0974e58001ac90ac5_202110271017147661635297434478.png</kict:photo_filename>
<kict:photo_size>1122621</kict:photo_size>
</kict:v_plans_photo>
</gml:featureMember>
</wfs:FeatureCollection>

I just used fetch to parse and fetch data like below:

let url = "/geoserver/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=kict:v_plans_photo&srsName=EPSG:4326&maxFeatures=10000&format_options=callback:getJson&cql_filter=INTERSECTS(geom, POINT (128.9880585 37.7161098))"

if (url) {
    fetch(url, {
       headers : { 
          'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then((response) => {
        console.log(response)
     },
     (error) => {
      this.setState({
         isLoaded: true,
         error
       });
       console.log(`fetch failed: ${this.state.error}`)
       }
     )
  }

How can I get data from that URL using fetch?

Proper way to return streaming data mongoose

I am trying to return some data that is streamed from an express server. Here is my code:

const cursor = Review.find({}).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
 console.log(doc);
 // Prints documents one at a time 
 res.status(200).json(doc); 
}

What is the proper way to return the data to the frontend so that doc ends up populating an array?

form wont export when search (search and export conflict)

I got one form with two submit button.

blade.php

    <form method="GET" id = "uploadForm">
        @csrf

        <div class="form-group">
            <button type="submit" value="Search" class="btn btn-info" id="search_btn" onclick="searchForm()">Search <i class="fa fa-search"></i></button> &nbsp;
            <button type="submit" value="Export" class="btn btn-success float-right" id="export_btn" onclick="exportForm()">Export <i class="fa fa-download"></i></button>
        </div>
    </form>

js file

function searchForm() get data and display as datatable
{
    let form = $('#uploadForm');
    let table = $('.datatable');

    form.attr('action', '/search').submit(function(e) {
        e.preventDefault();

        if ($.fn.DataTable.isDataTable(".datatable")) {
            table.DataTable().clear().destroy();
        }

        table.DataTable({
            processing: true,
            serverSide: true,
            bDestroy: true,
            bJQueryUI: true,
            ajax: {
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url : form.attr('action'),
                type : form.attr('method'),
                data : {
                    type: $("#type").val(),
                    from: $("#from").val(),
                    to  : $("#to").val(),
                },
            },
            columnDefs: [
                {'data': 'trx_id',      "targets": 0, title: "Trx ID"},
                {'data': 'type',        "targets": 1, title: "Type"},
                {'data': 'sender_id',   "targets": 2, title: "Sender ID"},
                {'data': 'receiver_id', "targets": 3, title: "Receiver ID"},
                {'data': 'amount',      "targets": 4, title: "Amount"},
                {'data': 'remark',      "targets": 5, title: "Method"},
                {'data': 'fee',         "targets": 6, title: "Fees"},
                {'data': 'afterFee',    "targets": 7, title: "Amount After Fees"},
                {'data': 'date',        "targets": 8, title: "Date"},
            ],
            error(){
                alert("error");
            }
        });
        // prevent submit multiple time
        e.stopImmediatePropagation();
        return false;
        // prevent submit multiple time
    });
}

function exportForm() //export data and download excel 
{
    $('#uploadForm').attr('action', '/export');
    $('#uploadForm').attr('target', '_blank').submit();
}

Search_form and export_form both work fine. But it have problem when I call search_form then call export_form, it will always go into search_form and will not download excel. I have run out of idea how to solve this issues.

Is the anyway to solve build error in nextjs?

I am building a site in nextJS. Recently I got an error when I run yarn run dev for building. Which is,

> Build error occurred
Error: Export encountered errors on following paths:
        /[page]/[pid]/[slug]
    at /home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/export/index.js:500:19
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Span.traceAsyncFn (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/trace/trace.js:74:20)
    at async /home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/build/index.js:987:17
    at async Span.traceAsyncFn (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/trace/trace.js:74:20)
    at async /home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/build/index.js:861:13
    at async Span.traceAsyncFn (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/trace/trace.js:74:20)
    at async Object.build [as default] (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/build/index.js:82:25)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I tried to solve it by adding solutions from the internet like adding log files inside
getStaticProps function. Nothing solving the issue.

Validation different message on the condition in password?

Hi i would like some help on my password field where i have this 2 type of validation message

first if the input for password when user click on submit button it be display please enter password!

2nd if the input for password is incorrect where it didnt meeet the requirement it display password do not meet the requirement!

Here my code for my html for the password and submit button

                                <div class="form-group row">
                                <label for="validationpassword" class="col-form-label passwordadduser">*Password:</label>
                                <div class="col-6 d-flex">
                                <input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="password" placeholder="Password"  required>
                                <i class="bi bi-eye-slash" id="togglePassword"></i>
                                <div style="margin-left: 15px;" class="invalid-tooltip password-empty" hidden>
                                    Enter a password!
                                </div>
                                <div style="margin-left: 15px;" class="invalid-tooltip password-notmeet" hidden>
                                    Password do not meet the requirement!
                                </div>
                                </div>
                            </div>

                        <button type="submit" class="btn-primary submitbutton">Add</button>

I have try a Jquery/JavaScript but seems not working i think i doing something wrong here

var empty = $(document.getElementById("password").value == '')
 if (empty){
 $('.pass').removeAttr('hidden');
 }
 else{

 $('.pass').attr('hidden', '');
 }

needed help as i not familiar with how the input should work ?

why the template ui did not show the vue data

I am a newbie with Vue, now I define the vue code like this:

import Vue from "vue";

export default Vue.extend({
  data: () => {
    message: "show message";
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div id="app">
    <div v-text="message"></div>
  </div>
</template>

why the UI did not show the Vue data message? this is my sandbox version code: https://codesandbox.io/s/loving-sea-snvfj?file=/src/App.vue:149-237