Dojo exportGrid as chunks

While the following code successfully exports the tabled data from the page to an Excel spreadsheet as a csv, it only does so up to around 9,000 rows- well below what Excel can accept. I’ve tried to break down the export into chunks of under 9,000 rows each, but haven’t had success. Might there be some syntax to do this, such as a Dojo piece to a while statement?

on(dom.byId("exportGrid"), "click", function(){

        xxxGrid.layout.setColumnVisibility(4, true);
        dijit.byId("xxxGrid").exportGrid("csv", function(exportData) {...

Thanks,
Dave

HTML5 canvas ellipse draws incorrectly

HTML5 Canvas seems to have an error when drawing an ellipse. Consider this simple example:

<html>
  <body>
    <canvas id="canvas" width="200" height="200"/>
    <script>
      var ctx = document.getElementById("canvas").getContext("2d");
      function draw(val) {
        ctx.moveTo(160,110);
        ctx.lineTo(val, 60.1418);
        ctx.closePath();
        ctx.ellipse(110, 110, 50, 50, 0, 4.63705, 0, true);
        ctx.stroke();
      }
      draw(106.2367);
      // draw(106.236);
    </script>
  </body>
</html>

I get the following image as a result:

ellipse 1

And if I simply replace draw(106.2367) with draw(106.236), I get a completely different result:

ellipse 2

I know this issue can be fixed by removing ctx.closePath(), but I want to know why this happened in the first place. Is this a bug?

For me this occurs in Chrome and Opera, but not Firefox or Safari.

is there a way to pass down props from parent component to child component

https://github.com/89missions/reactproblem/issues/1 I have posted all three files here please help.

react-dom.development.js:4312  Uncaught Type Error: props.UserName is not a function
at userValue (Editprofile.jsx:14:15)
at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
at invokeGuardedCallback (react-dom.development.js:4277:31)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:25)
at executeDispatch (react-dom.development.js:9041:3)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:7)
at processDispatchQueue (react-dom.development.js:9086:5)
at dispatchEventsForPlugins (react-dom.development.js:9097:3)
at react-dom.development.js:9288:12 this is the error message

i have a problem passing down props from a parent component down to children component. please im aware i can use useContext . buh thats not my problem now. i created a state variable in the parent component and passing down the variable and its function down to its children componet. your text

Cannot import better-sqlite3 in javascript file

I’m currently trying to import a module called better-sqlite3 into a javascript file for a database project I have coming up. When I run npm run in the command line everything works fine. I even see the database file being made. However, when I try to view the webpage in the browser I get the following error.

Uncaught TypeError: The specifier “better-sqlite3” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”

I’m really unsure as to what is going on, I install the module using the npm install command and it does show up in my node_modules folder in my projects root directory. I currently have my javascript file as type module in the package.json file. Any help would be appreciated.

Also, this is how I am importing the module import Database from 'better-sqlite3'

Javascript Array Object, return result in correct order

I have a created a array object. To simplify it I have just kept two fields, id and name.

I want to filter the mainArray and return the result in the order of the [3,9,1] as seen in the filterArray array object where with the code I am using sorts this to [1,3,9].

I have scaled down the array for simplicity.

mainArray = [
    { id: 1, name: 'AC Milan' },
    { id: 2, name: 'Juventus' },
    { id: 3, name: 'AS Roma' },
    { id: 4, name: "Napoli"},
    { id: 9, name: "Inter Milan"}
];

filterArray = [
    { id: 3 },
    { id: 9 },
    { id: 1 }
];

filteredArray = mainArray.reduce((acc, item, index) => {
    if(filterArray.some(filterItem => filterItem.id === item.id)) {
        // console.log(index);
        acc.push(item);
    }
    return acc;
}, []);

    
for(n=0; n<=filteredArray.length; n++){
    document.write(filteredArray[n].id+" - "+filteredArray[n].name+"<br/>");
};
    

WebAssembly module not initializing with Emscripten-generated JavaScript

I’m new to WebAssembly. Can you please help for the below issue? I was trying to get solutions from GitHub copilot but no luck.

I’m trying to create a minimal example of using WebAssembly with Emscripten. I have a simple C function that returns a fixed value, and I’m trying to call this function from JavaScript in an HTML file. However, the onRuntimeInitialized callback is never called, and the WebAssembly module does not seem to be initializing properly.

C code (minimal.c):

#include <stdint.h>

uint32_t get_fixed_value() {
    return 42;
}

I compiled the C code to WebAssembly using the following emcc command. I got minimal.js and minimal.wasm.

emcc minimal.c -o minimal.js -s EXPORTED_FUNCTIONS='["_get_fixed_value"]' -s EXPORTED_RUNTIME_METHODS='["cwrap"]' -s MODULARIZE

HTML file (minimal.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minimal WebAssembly Example</title>
    <script>
        var Module = {
            onRuntimeInitialized: function() {
                console.log("WebAssembly module initialized.");
                // Define the getFixedValue function
                window.getFixedValue = function() {
                    let getFixedValue = Module.cwrap('get_fixed_value', 'number', []);
                    return getFixedValue();
                };
                // Enable the button once the module is ready
                document.getElementById('getValueButton').disabled = false;
            }
        };
        console.log("Module object created.");
    </script>
    <script type="module" src="minimal.js"></script>
</head>
<body>
    <h1>Minimal WebAssembly Example</h1>
    <button id="getValueButton" onclick="getValue()" disabled>Get Fixed Value</button>
    <pre id="result"></pre>

    <script>
        function getValue() {
            if (typeof getFixedValue !== 'undefined') {
                let result = getFixedValue();
                document.getElementById('result').textContent = "Fixed Value: " + result;
            } else {
                alert("WebAssembly module is still loading. Please try again in a moment.");
            }
        }
    </script>
</body>
</html>

I am serving the files using a local web server (Python’s http.server).

Questions

Why is the onRuntimeInitialized callback not being called? I never see “Module object created.” on the browser console. The same issue is seen on Firefox and Chrome.

Thanks!

How to change the input color based on email existence using PHP, AJAX, and jQuery?

I hope you’re doing well. I’m fairly new to PHP, JavaScript, and programming in general, and I would greatly appreciate any guidance you can offer.

Problem:
I want to change the color of the email input field based on whether the entered email already exists in the database. If the email exists, the input box should turn red; if not, it should turn green. I am using PHP for the server-side logic and AJAX/jQuery for the client-side.

The Process:
When the email input loses focus, an AJAX request is sent to email_checker.php, where I check if the email already exists in the database.
I then use the response to change the color of the input box.

script.js (AJAX and jQuery):

$(document).ready(function() {
    $('form>input[name=email]').on('blur', checkEmail);  // Trigger when the email input loses focus
    
    function checkEmail() {
        var received_email = $('form>input[name=email]').val();  // Get the email value

        $.ajax({
            url: "servers/email_checker.php",  // Send request to this PHP file
            type: "POST",                     // HTTP POST method
            data: { email: received_email },  // Pass the email data
            success: function(result) {       // Handle the response
                if (result.available) {  // Email available
                    $('form>input[name=email]').css('color', 'green');
                } else {  // Email already exists
                    $('form>input[name=email]').css('color', 'red');
                    alert('Cet email est déjà utilisé.');  // Show error message
                }
            },
            error: function(err) {  // Error handling
                alert("Une erreur est survenue: " + err.statusText);
            }
        });
    }
});

servers/email_checker.php (Server-side logic):

<?php
session_start();
include("db.php");

if (isset($_POST["email"])) {
    $email = $_POST["email"];

    // Check if the email already exists
    $sql = "SELECT * FROM clients WHERE email = '$email'";
    $result = mysqli_query($conn, $sql);

    // Return JSON response
    if (mysqli_num_rows($result) > 0) {
        echo json_encode(["available" => false]);  // Email exists
    } else {
        echo json_encode(["available" => true]);   // Email available
    }
} else {
    echo json_encode(["available" => false]);  // No email sent
}
?>

new.php (Form and PHP code):

<?php
session_start();
include("db.php");
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style/style.css">
    <title>Créer un compte</title>
</head>
<body>
    <form action="new.php" method="post">
        <!-- Form fields for name, email, password, etc. -->
        <input type="email" name="email" placeholder="Email" required>
        <input type="password" name="motdepasse" placeholder="Password" required>
        <input type="submit" name="newbt" value="Créer un compte">
    </form>

    <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="site/script.js"></script>
</body>
</html>
<?php
if (isset($_POST["newbt"])) {
    $email = $_POST["email"];
    // Additional form processing code for inserting into the database
    $sql_check_email = "SELECT * FROM clients WHERE email = '$email'";
    $result_check = mysqli_query($conn, $sql_check_email);

    if (mysqli_num_rows($result_check) > 0) {
        echo "Cet email est déjà utilisé.";
    } else {
        // Insert the new user and activity into the database
        $sql1 = "INSERT INTO clients (firstname, lastname, sex, age, email, password) VALUES('$prenom', '$nom', '$sex', '$age', '$email', '$password')";
        $sql2 = "INSERT INTO activities (name, description, season) VALUES('$sport', '$des', '$season')";
        
        $result1 = mysqli_query($conn, $sql1);
        $result2 = mysqli_query($conn, $sql2);
        
        if ($result1 && $result2) {
            header("Location: index.php"); 
            session_destroy();
            exit();
        } else {
            echo "Une erreur est survenue. L'email est peut-être déjà utilisé.";
        }
    }
}
?>

Reset tabs to default resize window .. Javascript

I have that code .. its normal tabs javascript
I need when i resize the window .. To bigest then > 450px tabs back to default i mean tab2 automatic back to tab1 .. Cuz i use it in my menu

I tried more then tab code but .. I can’t …

Html

    <ul class="tabs">
        <li class="active" data-content=".one">One</li>
        <li data-content=".two">Two</li>
        <li data-content=".three">Three</li>
    </ul>
    <div class="content">
        <div class="one">cont one</div>
        <div class="two">2</div>
        <div class="three">cont three</div>
    </div>

Css

.tabs {
    display:flex;
    list-style:none;
    padding:0;
    margin:0
}
.tabs li {
padding:10px 30px;
background:white;
border-right:1px solid red;
cursor:pointer;
transition:0.5s
}
.tabs li.active,
.tabs li:hover {
background:pink;
}
.content {
background:pink;
}
.content > div {
padding:30px
}
.content div:not(:first-child){
    display:none
}

Javascript

let tabs = document.querySelectorAll(".tabs li");
let tabsArray = Array.from(tabs);
let divs = document.querySelectorAll(".two, .one, .three");
let divsArray = Array.from(divs);

    tabsArray.forEach((ele) => {
        ele.addEventListener("click", function (e){
            tabsArray.forEach((ele) => {
                ele.classList.remove("active");
            });
    
        e.currentTarget.classList.add("active");
        divsArray.forEach((div) => {
            div.style.display = "none"
        });
            document.querySelector(e.currentTarget.dataset.content).style.display = "block"
    });

    });

Changing background colors moving upwards

I found this code for changing background colors moving upward of the screen.
But now I want to get loop after last color to start with first one, not to go backward.
Just continuous go upwards and start from first color of the list.

body {
  margin: 0;
  height: 100vh;
  overflow: hidden;
}

.container {
  height: 400%;
  /* Contains four full viewport heights */
  animation: move 10s linear infinite;
}

.section {
  height: 100vh;
  /* Each section takes the full height of the viewport */
}

.section1 {
  background-color: #FF5733;
}


/* Red */

.section2 {
  background-color: #33FF57;
}


/* Green */

.section3 {
  background-color: #3357FF;
}


/* Blue */

.section4 {
  background-color: #F3FF33;
}


/* Yellow */

@keyframes move {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-75%);
  }
  /* Moves up through 4 sections */
  100% {
    transform: translateY(0);
  }
  /* Reset to start */
}
<div class="container">
  <div class="section section1"></div>
  <div class="section section2"></div>
  <div class="section section3"></div>
  <div class="section section4"></div>
</div>

How can I efficiently implement a debounce function in JavaScript?

I’m working on a web application where certain user interactions, like resizing the window or typing in a search input, trigger functions that can be called frequently in a short period. To improve performance, I want to implement a debounce function that limits how often these functions are executed.

Could someone provide an efficient way to implement a debounce function in JavaScript? Additionally, are there any best practices or potential pitfalls I should be aware of when using debouncing in a real-world application?

Removing integration from klaviyo dashboard but api’s still working

After revoking the integration from the Klaviyo dashboard, the following API call to refresh the token continues to return a 200 OK status and provides new access and refresh tokens.

export const refresh_token = async (user_id, rToken = null) => {
  let token;
  if (user_id > 0) {
    token = await prisma.refreshToken.findFirst({
      where: { user_id: user_id },
    });
  } else {
    token = {
      refresh_token: rToken,
    };
  }

  if (!token) {
    return json({ error: 'Refresh token not found' }, { status: 404 });
  }

  try {
    const response = await fetch('https://a.klaviyo.com/oauth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${btoa(`${process.env.KLAVIYO_CLIENT_ID}:${process.env.KLAVIYO_CLIENT_SECRET}`)}`,
      },
      body: new URLSearchParams({
        'grant_type': 'refresh_token',
        'refresh_token': token.refresh_token,
      }),
    });

    let res = await response.json();
    console.log("response _______________________________", res);

    if (!response.ok) {
      const errorData = await response.json();
      console.error('Error response from Klaviyo:', errorData);
      return json({ error: 'Failed to refresh token' }, { status: response.status });
    }

    const responseData = await response.json();

    if (user_id > 0) {
      await prisma.refreshToken.update({
        where: { id: token.id },
        data: { refresh_token: responseData.refresh_token },
      });

      await prisma.$disconnect();
    }

    return responseData.access_token;
  } catch (error) {
    console.error('Error during token refresh:', error);
    return json({ error: 'Failed to refresh token due to an unexpected error' }, { status: 500 });
  }
};

I tried making get event call to check weather tokens still working or not and unfortunately they work. I expect that removing integration from klaviyo dashboard should results in unauthenticated

Update embedded google sheet faster than 5 minutes

I have embedded google sheets in a web page. The google sheets are updating frequently but the update is reflected in my web page after 5 minutes. How can I update quicker? Runtime or at least every 10 seconds?

I have 8 sheets embedded in 8 I frames. So far I have tried bypass caching but for some reason this is also not working.

    </script>
    function refreshAllIframes() {
        const iframes = document.querySelectorAll('iframe');
        iframes.forEach(iframe => {
        const url = new URL(iframe.src);
        url.searchParams.set('timestamp', new Date().getTime()); 
        iframe.src=url.toString();
    
        });
      } 
       setInterval(refreshAllIframes, 10000);
    </script>
    
    
    <iframe id="screen1" src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTb_FLqllCprfiONXzn0qYD7N8KF7WBZuaH0sDANthjZBrwdVSwiz2KPFu7M5VHluxZ3io3sgr1_wnh/pubhtml?gid=0&headers=false&chrome=false&range=B:H&timestamp=<current-time>" width="100%" height="100%">
    </iframe>

7 more iframes like this.

Adding Base64 Images to a Docx in JS (or with a library)

I’m trying to code a little tool for my brother whom is a carpenter and i’m a bit stuck on one part of the process. (sorry for my english i’m not native)

Context : So the employees of my brother have to creates some files that can contains a lot of reports each reports have its own fields etc etc. So i did a form where you give your basic informations then you select the number of reports you want to make then when you are done with all your reports you can generate a docx of your file.

What i used: I used Docx templater to create a template of docx which is populated by my fields (everything is in JS) i’m not familiar at all with node so i included all the libs using and it worked so far.

So for the text it is working so far my code is populating the fields that are {between} and using the conditionning of docxtemplater.

The problem i have is for those reports a lot of picture have to be included in order to prove the state of things but i didn’t see at first that docxtemplater in order to use images you have to pay a license of 500$ a year. (and i don’t have the money for that ahahah) So i was able for now to store all of those pictures into array in base64 with clear id stating the field the number of report and all and also placing in the document the same id as the picture where it should appear.

But know i’m stuck because when i generate my docx i can see $1_1_picture_rooftile but i don’t know how to replace it with the base64 image stored in my array as key: 1_1_picture_rooftile related to base64 code of the image.

My goal is to after i generate the docx using docxtemplater and FileSaver take the output document and parse all those images tags i generated and replace those with the corresponding image.

I don’t know if i make sense but here is my code https://www.mediafire.com/file/eqidvjvsmrc1kr5/macullo8safe.rar/file

And this is my generate function at the end :

function generate() {
    collectImages();
    // Retrieve values from the form fields on page1
    const nom = document.getElementById('nom')?.value || '';
    const prenom = document.getElementById('prenom')?.value || '';
    const posteElement = document.querySelector('input[name="poste"]:checked');
    const numeroChantier = document.getElementById('numeroChantier')?.value || '';
    const address = document.getElementById('address')?.value || '';
    const city = document.getElementById('city')?.value || '';
    const postalCode = document.getElementById('postalCode')?.value || '';
    const hasNumeroChantierElement = document.querySelector('input[name="hasNumeroChantier"]:checked');

    // Check if the elements exist and log missing elements
    if (!posteElement) console.error('Element with name "poste" is missing or not checked.');
    if (!hasNumeroChantierElement) console.error('Element with name "hasNumeroChantier" is missing or not checked.');

    // If any required element is missing, stop execution
    if (!posteElement || !hasNumeroChantierElement) {
        console.error('Required form elements are missing.');
        return;
    }

    const poste = posteElement.value;
    const hasNumeroChantier = hasNumeroChantierElement.value === 'true';

    // Store current report data
    storeCurrentReportData();

    // Log the data to verify
    console.log({
        nom: nom,
        prenom: prenom,
        poste: poste,
        numeroChantier: numeroChantier,
        address: address,
        city: city,
        postalCode: postalCode,
        hasNumeroChantier: hasNumeroChantier,
        reports: reportsDataArray
    });

    // Load the DOCX template
    loadFile('./template.docx', function (error, content) {
        if (error) {
            throw error;
        }
        const zip = new PizZip(content);
        const doc = new window.docxtemplater(zip, {
            paragraphLoop: true,
            linebreaks: true
        });


        // Create a data object with the retrieved values and report data
        const emptyTab = [];
        const fullTab = [];

        fullTab.push({"name":"toto"});
        fullTab.push({"name":"eliott"});


        const dataTab={
            empty:emptyTab,
            full:fullTab
        };


        const data = {
            nom: nom,
            prenom: prenom,
            poste: poste,
            numeroChantier: numeroChantier,
            address: address,
            city: city,
            postalCode: postalCode,
            hasNumeroChantier: hasNumeroChantier,
            reports: reportsDataArray
        };

        // Set the data in the template
        doc.setData(data);

        try {
            // Render the document
            doc.render();
        } catch (error) {
            const e = {
                message: error.message,
                name: error.name,
                stack: error.stack,
                properties: error.properties,
            };
            console.log(JSON.stringify({ error: e }, null, 2));
            throw error;
        }


                const out = doc.getZip().generate({ type: 'blob' });
                saveAs(out, 'output.docx');
    });
}