The column heading format is not working in export excel sheet using sheet js

I am trying to add formation on column heading(background and text color) in excel sheet when click the Export to Excel button. It is not working in exported excel file. The table made in HTML table tags.I tried different ways but these methods are not working.
I have made the JS fiddle example please check.

    function exportToExcel() {
        const table = document.getElementById('rep_groupingTable_data');
      const rows = table.getElementsByTagName('tr');

      // Create a new Workbook
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.aoa_to_sheet([]);

      const headers = [];
      const cells = rows[0].getElementsByTagName('th');

      // Loop through table headers, skipping the first column if necessary
      for (let j = 0; j < cells.length; j++) {
          if (j !== 0 || !cells[j].classList.contains('re_has_no_summary')) {
              headers.push(cells[j].textContent.trim());
          }
      }

      // Add column headers to the worksheet
      XLSX.utils.sheet_add_aoa(ws, [headers]);

      // Loop through each row of the table to add data
      for (let i = 1; i < rows.length; i++) {
          const rowData = [];
          const cells = rows[i].getElementsByTagName('td');

          // Skip rows with the class "re_has_no_summary"
          if (!rows[i].classList.contains('re_has_no_summary')) {
              for (let j = 0; j < cells.length; j++) {
                  // Skip the first cell if it has the class "re_has_no_summary"
                  if (j !== 0 || !cells[j].classList.contains('re_has_no_summary')) {
                      rowData.push(cells[j].textContent.trim());
                  }
              }
              XLSX.utils.sheet_add_aoa(ws, [rowData], { origin: -1 });
          }
      }

      // Append the worksheet to the workbook
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // Generate Excel file
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      saveAs(blob, 'Report.xlsx');
    }
    
    function s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
  }
#report_expor_table_data_se {
  margin-top:20px;
}
    <!doctype html>
    <html>
    <head>
    <title>Our Funky HTML Page</title>
    <meta name="description" content="Our first page">
    <meta name="keywords" content="html tutorial template">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.0/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    </head>
    <body>
   <h4>
Export HTML Table Into ExcelSheet
</h4>
<!-- Add an HTML button to trigger the export -->
<button onclick="exportToExcel()">Export to Excel</button>

<!-- Your HTML table -->
<div id="report_expor_table_data_se" >
    <table style="border-bottom: 1px solid #dddee2" id="rep_groupingTable_data" width="100%" cellpadding="0" cellspacing="0" class="report_grouping_table">
        <thead>
            <tr>
                <th style="text-align: left;background: #36a7c4;border-bottom: 1px solid #dddee2;">Status</th>
                <th style="text-align: left;background: #36a7c4;border-bottom: 1px solid #dddee2;">Code</th>
                <th style="text-align: left;background: #36a7c4;border-bottom: 1px solid #dddee2;">Name</th>
            </tr>
        </thead>
        <tbody>
            <!-- Your table content -->
            <tr>
                <td style="text-align: left;  padding: 10px 10px;font-size: 14px;color: #4f5764;line-height: 1.5em;border-top: 1px solid #dddee2;border-left: 1px solid #dddee2;">active</td>
                <td style="text-align: left;  padding: 10px 10px;font-size: 14px;color: #4f5764;line-height: 1.5em;border-top: 1px solid #dddee2;border-left: 1px solid #dddee2;">CUS001</td>
                <td style="text-align: left;  padding: 10px 10px;font-size: 14px;color: #4f5764;line-height: 1.5em;border-top: 1px solid #dddee2;border-left: 1px solid #dddee2;">Demo Customer</td>
            </tr>
            <tr>
                <td style="text-align: left;  padding: 10px 10px;font-size: 14px;color: #4f5764;line-height: 1.5em;border-top: 1px solid #dddee2;border-left: 1px solid #dddee2;">inactive</td>
                <td style="text-align: left;  padding: 10px 10px;font-size: 14px;color: #4f5764;line-height: 1.5em;border-top: 1px solid #dddee2;border-left: 1px solid #dddee2;">00009</td>
                <td style="text-align: left;  padding: 10px 10px;font-size: 14px;color: #4f5764;line-height: 1.5em;border-top: 1px solid #dddee2;border-left: 1px solid #dddee2;">Jean</td>
            </tr>
        </tbody>
    </table>
</div>




    </body>
    </html>

https://jsfiddle.net/v473grka/7/

Is there a way to make a web page pass a variable to Google script and send the data back during the webpage onload for the output display?

I have a Google spreadsheet and I want to process all row data using Google script. The problem is that I am not able to make my website pass a variable to Google script. The Google script should accept the variable and process the data. After the data is processed, Google script should be able to pass the processed condition back to the web page. Please help me!

I already have made a Google script that will process the data from the webpage. The webpage should pass it’s url string and Google script should process the url with if else. I have tried using API but still not working. I am not able to pass the variable from my website to Google script

Issue retrieving JSON from Java Servlet using JavaScript fetch method

Working with dynamic web project on Eclipse, I have a form in my HTML file that sends user inputs to a Java Servlet. From the Servlet, I am processing the information and want to return JSON back and I’m trying to have JavaScript pick them up but nothing happens in console except error with status of 500 and the one that says “Request failed SyntaxError: Unexpected token ‘<‘, “<!doctype “… is not valid JSON” when I initially run the project on server.
When I submit the form, I get the JSON that I want print on a new webpage (localhost:port#/project_name/Servlet) but I don’t see it in console.

My servlet:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    // Process data 

    PrintWriter out = response.getWriter();
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.println("{");
    out.println(""Name":" + """ + name_var + "",");
    out.println(""Phone":" + """ + phone_var + "",");
    out.println(""Price":" + """ + price_var + "",");
    out.println(""Location":" + """ + location_var + "",");
    out.println("}");
    out.close();
} 

JavaScript:

function fetchResults(){

let baseURL = window.location.origin + "/<project_location>/";
var url = new URL("<ServletName>", baseURL);
fetch(url)
    .then(response => response.json())
    .then(data =>{
        console.log(data);
    })
    .catch(error=> {
        console.log('Request failed', error);
    });
}
document.addEventListener('DOMContentLoaded', fetchResults); 

I think I’m getting the errors because I am using wrong event listener to invoke fetch method. It gets invoked not when I submit the form but when I initially load the project.

The error “Request failed SyntaxError: Unexpected token ‘<‘, “<!doctype “… is not valid JSON” is invoked from “console.log(‘Request failed’, error);” line of JavaScript.

PHP echo $CVisitors don’t work in .php file

This code displays blank in my browser, and my JavaScript doesn’t even work. Even when I try and on click events with HTML, my JavaScript doesn’t work. It’s like it doesn’t get launched or executed on mean. same issue with my PHP. It seems like it’s not getting executed. <?php $CVisitors = 0; $CVisitors + 1; echo $CVisitors; ?>

How do I prevent clicking multiple decimal point from the user in a javaScript calculator

I’ve created a javaScript calculator with html, css and javascript. Here i’ve created onclick events with function , and for all the button in the calculator i’ve created a single function now I’m not able to prevent clicking multiple decimal point from the user.

I’ve tried with loops and the Includes method tried to do it by getting the index of the firs decimal point inputed by the user but didn’t work. I want that in a input field there will be one decimal point and if the user try to input multiple decimal point, it won’t work.

The useState set method is not reflecting change in the following cod

this is code for creating post when code is refreshed and the first post is created the image link which should be set into postImg but the if i another post without refreshing tha post will have postimg field fill with image link but if refreshed the same problem continues

and the api for img to link work’s as it log’s the link very time

here is the code:

import React, { useEffect, useState } from "react";
import state from "../../helpers/state";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import toast from "react-hot-toast";
import { useSnapshot } from "valtio";
interface Post {
  userId: string;
  postMessage: string;
  postImg?: string;
}
const CreatePost = () => {
  const snap = useSnapshot(state);
  const [img, setImg] = useState<Blob>();
  const [loading, setLoading] = useState(false);
  const [post, setPost] = useState({
    title: "",
    postMessage: "",
    userId: snap.userid,
    postImg: "",
  });

  const navigate = useNavigate();
  useEffect(() => {
    state.logutBtn = false;
    // if (state.isAuth) {
    //   navigate("/login");
    // }
  }, []);

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const imageFile = e.target.files[0];
      setImg(imageFile); // Store the image file directly in the state variable
    }
  };

  function addImg(link: string) {
    setPost((prevPost) => ({
      ...prevPost,
      postImg: link,
    }));
  }

  const createPost = async () => {
    if (img) {
      try {
        setLoading(true);
        const formData = new FormData();
        formData.append("file", img);
        const imageUploadResponse = await axios.post(
          "http://localhost:3000/image/upload",
          formData
        );
        const imageUrl = imageUploadResponse.data.url;
        console.log(imageUrl);

        // Set the image URL to user.profileImg
        addImg(imageUrl);

        console.log(post);

        // Sending user data to "http://localhost:3000/api/create"

        if (post.postImg.length !== 0) {
          const response = await axios.post(
            "http://localhost:3000/post/create",
            post
          );
          console.log(response.data);
          toast.success("Post Created");
        } else {
          toast.error("Please try again");
        }

        // navigate("/login");
        setLoading(false);
      } catch (error: any) {
        console.error("Error:", error);
        toast.error(error.response.data.message);
      } finally {
        setLoading(false);
      }
    } else {
      console.log("Please select an image before uploading.");
      toast.error("Please select the image");
    }
  };

  return (
    <div className="max-w-md  mt-8 p-6 bg-white rounded-md shadow-md">
      <h2 className="text-2xl font-semibold mb-4">Create Post</h2>
      <input
        type="text"
        placeholder="Title"
        className="w-full mb-4 p-2 border rounded-md"
        onChange={(e) => setPost({ ...post, title: e.target.value })}
      />
      <input
        type="text"
        placeholder="Message"
        className="w-full mb-4 p-2 border rounded-md"
        onChange={(e) => setPost({ ...post, postMessage: e.target.value })}
      />

      {img && (
        <img
          src={URL.createObjectURL(img)}
          alt="img"
          className="w-1/2 mx-auto"
        />
      )}

      <label htmlFor="img">
        <img
          className="w-10 m-2"
          src="https://www.svgrepo.com/show/458751/img-load-box.svg"
          alt=""
        />
      </label>
      <input
        type="file"
        id="img"
        name="img"
        className="mb-4 hidden"
        onChange={handleImageChange}
      />
      <button
        onClick={createPost}
        className="w-full disabled:bg-red-500 disabled:text-black bg-blue-500 text-white p-2 rounded-md hover:bg-blue-600"
        disabled={loading}
      >
        {loading ? "Creating Post..." : "Create Post"}
      </button>
    </div>
  );
};

export default CreatePost;

Difference between importing file from the same directory and from node_modules

Why is typescript compiler fine with importing from JS file from local directory, but complains about importing from node_modules?

Code:

import { t2 } from "./t1.js"
t2.hello();

import { mat4 } from "./node_modules/gl-matrix/esm/index.js";
mat4.create();

Error:

main.ts:4:22 - error TS7016: Could not find a declaration file for module './node_modules/gl-matrix/esm/index.js'. '/.../node_modules/gl-matrix/esm/index.js' implicitly has an 'any' type.

4 import { mat4 } from "./node_modules/gl-matrix/esm/index.js";
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If I comment the last two lines it compiles fine.

Repro steps.

npm install --save-dev typescript gl-matrix

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "outDir": "./obj",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "allowJs": true
  }
}

t1.js (mimics content of index.js from gl-matrix):

import * as t2 from "./t2.js"
export { t2 };

t2.js (mimics content of mat4.js from gl-matrix):

export function hello() {
    return "hello";
}

Content Security Policy blocking ‘eval’ in Laravel project on live server – Page content not displaying

Description:
I am currently facing an issue with my Laravel project when deployed to a live server. It seems that the Content Security Policy (CSP) is blocking the use of ‘eval’ in JavaScript, and as a result, my content is not displaying as expected.

Problem:

  1. The content displays correctly in a local environment but encounters issues on the live server.
  2. After investigating, it appears that the CSP is blocking the ‘eval’ function in JavaScript, which is used in my project.

I am seeking guidance on how to address this issue. Thanks!

$response->header(‘Content-Security-Policy-Report-Only’, “default-src ‘self’; script-src ‘self’ ‘unsafe-eval’; style-src ‘self’ https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css https://cdn.bootstrap.com;; report-uri /csp-report-endpoint”);

Tried changing my CSP to Report-Only, it ignore the security issue but not the ‘eval’ error. and the content still not displayed on the live server

populate a SELECT Dropdown List with JSON Data using JavaScript

I want to populate a SELECT Dropdown List with JSON Data using JavaScript
i have sample data

sampledata  =  [{ "Districtname": "CENTRAL DELHI", "ID": 1 }, { "Districtname": "NORTH DELHI", "ID": 2 }, { "Districtname": "NORTH EAST DELHI", "ID": 3 }, { "Districtname": "NORTH WEST DELHI", "ID": 4 }, { "Districtname": "SOUTH DELHI", "ID": 5 }, { "Districtname": "SOUTH EAST DELHI", "ID": 6 }, { "Districtname": "SOUTH WEST DELHI", "ID": 7 }, { "Districtname": "WEST DELHI", "ID": 8 }]
success: function(data) {
    var distList = data.d;
    console.log(distList);
    //consoleoutput =  [{ "Districtname": "CENTRAL DELHI", "ID": 1 }, { "Districtname": "NORTH DELHI", "ID": 2 }, { "Districtname": "NORTH EAST DELHI", "ID": 3 }, { "Districtname": "NORTH WEST DELHI", "ID": 4 }, { "Districtname": "SOUTH DELHI", "ID": 5 }, { "Districtname": "SOUTH EAST DELHI", "ID": 6 }, { "Districtname": "SOUTH WEST DELHI", "ID": 7 }, { "Districtname": "WEST DELHI", "ID": 8 }]
    var s = '<option value="-1">Please Select a Distic</option>';
    for (var i = 0; i < distList.length; i++) {
        s += '<option value="' + distList[i].ID + '">' + distList[i].Districtname + '</option>';
    }
    $("#dist").html(s);

}

i tried another approach

$.each(distList, function (key, value) {
  $('#dist').append('<option value="' + key + '">' + value + '</option>');
});

but

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"Districtname":"CENTRAL.................... ,{"Districtname":"WEST DELHI","ID":8}]

plz help

Read strings from ReadableStream line-by-line

I’m using Bun to communicate with a stockfish child process.

let process = Bun.spawn(["stockfish"], { stdin: "pipe" });

The stockfish CLI reads commands from stdin and writes commands to stdout. Once the process is started, it stays alive, responding to commands without closing.

When calling Bun.spawn with these parameters, Bun returns an instance of Subprocess<"pipe", "pipe", "inherit">. This object has a stdout property which is an instance of ReadableStream<Uint8Array> for accessing the data.

Since stockfish always outputs a newline with each line it prints, I need to be able to read strings from the stream line-by-line. Ideally, I could do something like this.

process.stdin.write(`isreadyn`);
process.stdout.readLine(); // "readyok"

What’s the best way to accomplish this?

The time it takes for PageMethod to be received by code behind is not consistent

I am quite new to webpage development.

I have a ASP .NET Web Application. On my webpage, I have several controls, that when clicked, will call a PageMethod to the code behind. My concern is, when I click any of these controls, and the respective PageMethod is fired, the amount of time it takes until the WebMethod in the code behind get hit is not consistent. Sometimes it will happen within 1s, but sometimes it will take 15s. The PageMethod always fires immediately after the click. It is not like these PageMethods are being called quickly either, so I wouldn’t think any backup/lock is happening. I am looking to make it so my PageMethods are always received by the code behind somewhere around 1s. I can’t seem to find anyone else with this issue. I am hoping someone can explain/guide me to a solution. Below is a code snippet of one of these click instances:

Javascript side:

<canvas id="DisplayCanvas" onclick="onRadarEchoClick(event)"> </canvas>

    function onRadarEchoClick(e) {
                        //code stuff.
    
                        //Queue up radar echo click to be processed.
                        radarEchoQueue.push([convertedX, convertedY, e.button]);
        
                        var radarEchoInterval = setInterval(function () {
                            if (radarEchoReady) {
                                radarEchoReady = false;
                                clearInterval(radarEchoInterval);
                                const click = radarEchoQueue.shift();
                                PageMethods.OnRadarEchoClick(click[0], click[1], click[2], onRadarEchoSuccess);
                            }
                        }, 100);
                    }
        
                    function onRadarEchoSuccess() {
                        //The server has successfully processed the last radar echo click.
                        radarEchoReady = true;
                    }

Code behind side (C#):

    [WebMethod]
            public static void OnRadarEchoClick(double xComponent, double yComponent, int button)
            {
                //code stuff.
                //There is where my breakpoint will take a random amount of time (1-15s) to be hit.
            }

understanding promise chaining with catch and then

I am unable to understand the result of the below promise chain

function job(state) {
    return new Promise(function(resolve, reject) {
        if (state) {
            resolve('success');
        } else {
            reject('error');
        }
    });
}

let promise = job(true);

promise

.then(function(data) {              ///1
    console.log(data);

    return job(true);
})

.then(function(data) {              ///2
    if (data !== 'victory') {
        throw 'Defeat';
    }

    return job(true);
})

.then(function(data) {              ///3
    console.log(data);
})

.catch(function(error) {              ///4
    console.log(error);

    return job(false);
})

.then(function(data) {              ///5
    console.log(data);

    return job(true);
})

.catch(function(error) {              ///6
    console.log(error);

    return 'Error caught';
})

.then(function(data) {              ///7
    console.log(data);

    return new Error('test');
})

.then(function(data) {              ///8
    console.log('Success:', data.message);
})

.catch(function(data) {              ///9
    console.log('Error:', data.message);
});

The output is

success
Defeat
error
Error caught
Success: test

I can see why ‘success’ and ‘Defeat’ are printed.
But then I am confused. Why 3, 4,5 are skipped and it executes 6?
Then since 7 throws an error, shouldn’t 9 be executed instead of 8?

i want to update un var inside a url after click on one of button too use outiside the scope in the fetch

i want to update the url with different value depend with button you click to use after outside in the fetch primary objectif is to have variable who are update when click that i can use inside the url who change when click on button and the url i can implement after in other function with the value update

var elementId = "";
var url = ""; // Variable globale pour stocker l'URL

function updateElementId(element) {
  elementId = element.value;

  test();

  return elementId;
}

function test() {
  url = `https://v3.football.api-sports.io/standings?league=${elementId}&season=2023`;
  return url;
}
console.log(url);
console.log(test());

console.log(test());
<div>
  <button id="button1" value="5" onclick="updateElementId(this)">
    Bouton 1
  </button>
  <button id="button2" value="45" onclick="updateElementId(this)">
    Bouton 2
  </button>
  <button id="button3" value="3" onclick="updateElementId(this)">
    Bouton 3
  </button>
  <button id="button4" value="75" onclick="updateElementId(this)">
    Bouton 4
  </button>
  <button id="button5" value="42" onclick="updateElementId(this)">
    Bouton 5
  </button>
</div>

i want to update the url when click on the button and change the value in var inside the url to use in the fetch after