Show more than 20 columns of data table in a webpage using jQuery DataTables and MySQL

Hi all what I’m trying to do is how to display number of columns using datatables for 20+ columns in the same webpage. I am using MySQL, jQuery datatables and html.

So this is m MySQL query:

select LOT_LOCATION, `Zone Attribute`, a.LOTID, Design_ID, ifnul(Board_ID,'') as Board_ID1, QA_WORK_REQUEST_NUMBER, QA_PROCESS_TYPE, QA_PROCESS_NAME, CURRENT_QTY, Date, Temperature, Humidity, CONCAT(b.Zone1_Voltage, 'V, ', b.Zone1B_Voltage, 'V, ',b.Zone1C_Voltage, 'V') AS Voltage_1, CONCAT(b.Zone1_Current, 'A, ', b.Zone1B_Current, 'A, ',b.Zone1C_Current, 'A') AS Current_1, CONCAT(b.Zone2_Voltage, 'V, ', b.Zone2B_Voltage, 'V, ',b.Zone2C_Voltage, 'V') AS Voltage_2, CONCAT(b.Zone2_Current, 'A, ', b.Zone2B_Current, 'A, ',b.Zone2C_Current, 'A') AS Current_2, CONCAT(b.Zone3_Voltage, 'V, ', b.Zone3B_Voltage, 'V, ',b.Zone3C_Voltage, 'V') AS Voltage_3, CONCAT(b.Zone3_Current, 'A, ', b.Zone3B_Current, 'A, ',b.Zone3C_Current, 'A') AS Current_3, CONCAT(b.Zone4_Voltage, 'V, ', b.Zone4B_Voltage, 'V, ',b.Zone4C_Voltage, 'V') AS Voltage_4, CONCAT(b.Zone4_Current, 'A, ', b.Zone4B_Current, 'A, ',b.Zone4C_Current, 'A') AS Current_4, CONCAT(b.Zone5_Voltage, 'V, ', b.Zone5B_Voltage, 'V, ',b.Zone5C_Voltage, 'V') AS Voltage_5, CONCAT(b.Zone5_Current, 'A, ', b.Zone5B_Current, 'A, ',b.Zone5C_Current, 'A') AS Current_5, CONCAT(b.Zone6_Voltage, 'V, ', b.Zone6B_Voltage, 'V, ',b.Zone6C_Voltage, 'V') AS Voltage_6, CONCAT(b.Zone6_Current, 'A, ', b.Zone6B_Current, 'A, ',b.Zone6C_Current, 'A') AS Current_6 from Lab_WIP_History a LEFT join chamber_data b ON a.LOT_LOCATION = b.Testtag  LEFT JOIN chamber_data_1 c ON a.LOTID = c.lotid

This is the MySQL table it generates (there are 24 columns title with 24 columns of data):

LOT_LOCATION, Zone Attribute, LOTID, Design_ID, Board_ID1, QA_WORK_REQUEST_NO, 
QA_PROCESS_TYPE, QA_PROCESS_NAME, CURRENT_QTY, Date, Temperature, Humidity, Voltage_1, 
Current_1, Voltage_2, Current_2, Voltage_3, Current_3, Voltage_4, Current_4, Voltage_5, 
Current_5, Voltage_6, Current_6
'SGHAST.0064', '3', 'CVC66L2.11', 'J39E', '', '106544', 'ROBUSTNESS VALID', 'HAST 110C', '40', 
'2022-06-13 13:39:42', '109.98', '85.08', '3.6V, 1.95V, V', '0.0A, 0.11A, A', '3.6V, 1.95V, 
V', '0.0A, 0.1A, A', '3.6V, 1.95V, V', '0.0A, 0.12A, A', '3.6V, 1.95V, V', '0.0A, 0.12A, A', 
'3.6V, 1.95V, V', '0.0A, 0.12A, A', '3.6V, 1.95V, V', '0.0A, 0.12A, A'

And this is my JavaScript code:

<script>
$(document).ready(function() {

var table = $('#elogbooktable').DataTable( {
  "ajax": {url: "testing_getdetaildata.php", dataSrc: ""},
      'scrollCollapse': false,
      'deferRender':    true,
      'scroller':       true,
      'lengthMenu':     [[50, 75, 100, 200, -1], [50, 75, 100, 200, 'ALL']],
      'iDisplayLength': 50,
      'order': [[ 4, "asc" ]],
      'orderCellsTop' : true,
      'columnDefs': [ {
        'targets': 2,
        'createdCell': function(td, cellData, rowData, row, col) {
          if(rowData[2]) {
              $(td).html("<a href='http://mamweb.sing.micron.com/MAMWeb/bin/MAMWeb.pl?APP=MAMQASI&ACTION=REPORT&REPORTID=Status&MATYPE=78&FORMAT=HTML&CATEGORIES=ALL&ID="+rowData[2]+"' target='_blank'>"+rowData[2]+"</a>");
          }
        }
      }, {
        'targets': 9,
        'createdCell': function(td, cellData, rowData, row, col) {
          if(rowData[9]) {
              $(td).text(moment(rowData[9]).format('MM-DD-YYYY hh:mm A'));
          }
        }
      }, {
        'targets': 10,
        'createdCell': function(td, cellData, rowData, row, col) {
          if(rowData[10]) {
              $(td).text(rowData[10] + " C");
          }
        }
      } ,{
        'targets': 11,
        'createdCell': function(td, cellData, rowData, row, col) {
          if(rowData[11]) {
              $(td).text(rowData[11] + " %RH");
          }
        }
      }],
      'filterDropDown': {                                       
                    columns: [
                        { 
                            idx: 5
                        }
                    ],
        bootstrap: true
                },
     rowCallback: function(row, data, index){
        if(new Date(data[42]) < Date.now()){
        $(row).find('td:eq(42)').css('background-color', '#f8d7da');
      }
    },
});

  <?php $i=13; 
 foreach($columns as $id=>$value) { 
     print "showHideColumn($id, $i);n";
     $i++;
   } 
  ?>    

//Add a text search box to each footer cell
table.columns().every( function () {
  $(this.footer()).html("<input type='text' style='width:100%;' placeholder='Search'/>");
});

//Full table search functionality
// Column search function       
table.columns().every( function () {
  var that = this;
  $( 'input', this.footer() ).on( 'keyup change', function () {
    if ( that.search() !== this.value ) {
      that.search( this.value, true ).draw();
    }
  });
});

var buttons = new $.fn.dataTable.Buttons(table, {
 'buttons': ['pageLength','copyHtml5',
        {
          extend: 'excelHtml5',
        },
        {
          extend:  'print',
        }]
}).container().appendTo($('#envdetail_wrapper .col-sm-6:eq(0)'));

setInterval( function () {
  table.ajax.reload();
}, 300000 );

});



function showHideColumn(id, number) {
var dtable = $('#elogbooktable').DataTable();

if(dtable.column(number).visible() === true) {
  if($(id).attr("class").includes("btn-primary")) {
      $(id).removeClass("btn-primary");
      $(id).addClass("btn-default");
    }
    dtable.column(number).visible(false);
}
else {
  if($(id).attr("class").includes("btn-default")) {
      $(id).removeClass("btn-default");
      $(id).addClass("btn-primary");
    }
    dtable.column(number).visible(true);
}
}

I tried using ‘scrollX’: true function but it still only shows me first 13 columns and I am unable to scroll horizontally. Is there a way to solve this display issue? Thank you any help is appreciated!

Convert string to import call in React

I have the following imports in my project:

import video1 from '../../assets/video1.mp4';
import video2 from '../../assets/video2.mp4';

and the following code:

...
constructor(props){
    super(props)
    this.state={
        videoURL: this.props.source,
    }
}
render(){
return(
<div className='app'>
    <video onTimeUpdate={(e) => this.videoBuffer(e)} id="videoPlayer" ref="VidRef" src={this.state.videoURL} muted={this.state.muteVideo} onClick={(e) => this.togglePlayPause(e)} autoPlay></video>
</div>
)}

after i get back the props from another component, they appear as string, ie, “video1” and “video2” which are then passed to src of the video component.
Unfortunately i am not able to render the video component as

src="video1"

is not valid. Is there a way to convert “video1” to the import that i have made above in line 1?
since i have thousands of videos, i cannot use arrays.

i also do not want to use dangerouslysetinnerhtml to avoid any openings to xss attacks.

when we type a text in input box than loader is start loading. but we want loader only work when we press enter key

when we type a text in the input box then the loader starts loading. but we want loader only to work when we press enter key

// Function is called when user enter input any text in filter box
$scope.gridGuestsApi.core.on.filterChanged($scope, function () {
$scope.direct = false;
$scope.oppvmware_guestlist_loading = true; // To show the loader
});

this is html code

How can i add where condition in firebase query based on if condition?

I am writing a query in firebase, but I want to add where() condition based on the condition. Like if some values are exist then where() should be included otherwise normal query should be run as it is. Below is my code. I checked using console.log if condition is passed but the query returns all results. Please help me to fix this issue.

const loadPapers = () => {
  let t = savedTopifyPapers
  if (queryParams.value.key && queryParams.value.value) {
    t.orderBy('timeStamp')
      .limit(limit.value)
      .where(queryParams.value.key.toString(), '==', queryParams.value.value)
  } else {
    t.orderBy('timeStamp').limit(limit.value)
  }
  t.onSnapshot((snapshot) => {
    const _lastDoc = snapshot.docs[snapshot.docs.length - 1]
    firstVisible.value = snapshot.docs[0]
    if (_lastDoc) {
      lastDoc.value = _lastDoc
    }
    if (snapshot.empty) {
      loadingData.value = false
    }
    papersData.value = snapshot.docs.map((doc) => {
      const data = doc.data()
      const id = doc.id
      loadingData.value = false
      return { id, ...data }
    })
    papersDataLength.value = papersData.value.length
  })
}

Any solution appreciated!

Warning: unstable_flushDiscreteUpdates when rendering component in React

I’ve been trying to render a component using map, the render happens but with a warning:

Warning: unstable_flushDiscreteUpdates: Cannot flush updates when
React is already rendering.

MyBooks.js

import React, { useState, useEffect } from 'react';
import ActionAreaCard from '../components/ActionAreaCard';

const MyBooks = ({address}) => {

    const [metadata, setMetadata] = useState([]);

    const URL = `http://localhost:3001/api/tatumapi`;
    const chain = 'CELO';
    const params = { address: address, chain: chain };

    useEffect(() => {
        fetch(URL,
            {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            })
            .then(response => response.json())
            .then(data => setMetadata(
              (data.data).map((data2) => {
                return data2.metadata.map((data3) => {
                  return data3;
                })
              })
            ))
    }, [])

    return (
      <div>
        {metadata.map((data4) => {
          return (
            <div>
              {data4.map(({metadata}) => {
                return (
                  <div>
                    {metadata!= null && console.log(metadata)}
                    {metadata!=null && <ActionAreaCard name={metadata.name} description={metadata.description} image={metadata.image}/>}
                  </div>
                )
              })}
            </div>
          )
        })}
      </div>
    )
}

export default MyBooks;

Console output:

{description: 'The very first edition', name: 'BOOK', image: 'ipfs://bafkreidny67q3xxjulstouk7vzp6bomdbnokg3zzhg6k4gqbdtutqzz5h4'}
description: "The very first edition"
image: "ipfs://bafkreidny67q3xxjulstouk7vzp6bomdbnokg3zzhg6k4gqbdtutqzz5h4"
name: "BOOK"
[[Prototype]]: Object

Why I’m getting this warning and how can I solved it?

Custom components does not work in React Native

I am new to react native and trying to make a small user input form, but my code does not work well.

I made a class that will create label and text input, but style does not work for my class, Form1. The class in the same file App.js worked, but importing from another js file did not.

Can someone help me to figure out the solution and why it happens?

App.js

import React, { useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
import Form1 from './Parts/Form1';

export default function App() {
const [name, setName] = useState('Haruku');
const [age, setAge] = useState('30');

return (
    <View style={styles.container}>
        <StatusBar style="auto" />
        <View>
            <Text style={styles.centerBox} borderWidth="1">Enter name: </Text>
            <TextInput
                style={styles.input}
                placeholder='Example'
                onChangeText={(val) => setName(val)} />
            <Form1 />
            <Text>name: {name}, age: {age}</Text>
        </View>
    </View>
  );
}

const styles = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
},
input: {
    borderWidth: 1,
    borderColor: '#777',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 8,
    margin: 10,
    width: 200,
},
centerBox: {
    alignSelf: 'center',
    textAlign: 'center',
    borderWidth: 1,
    width: 150,
},
buttonContainer: {
    marginTop: 20,
    backgroundColor: "#0000FF",
},
});

Form1.js

import { StyleSheet, Text, View,TextInput } from 'react-native';

class Form1 extends React.Component {
    render() {
        return (
            <View>
                <Text style={styles2.centerBox}>Age: </Text>
            <TextInput style={styles2.input} placeholder='Example' />
        </View>
    )
}
}

const styles2 = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
},
input: {
    borderWidth: 1,
    borderColor: '#777',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 8,
    margin: 10,
    width: 200,
    placeholder: "Ex",
},
centerBox: {
    alignSelf: 'center',
    textAlign: 'center',
    alignItems: 'center',
},
});

export default Form1;

Execute two function at the same time with JavaScript

I have the following problem: I have two components in React. The first component executes a function that runs a timer. The timer uses the method setInterval() to decresse the seconds on each call untill cero. When the timer reaches 0 I call clearInterval() and this function stops. During the period of time in which the timer is runing, I have a second component that has a button. That button has an onClick property that calls a function. This function sends a request to my node.js server. Bare in mind that while the button is being click and its function is called, the timer is constantly calling the fucntion that descresses the seconds.

So I find that when the button in the second component fires its function, there is no request reaching the server. I have tested that the connection between client and server and the routes work using Postman. I have also tested that my onClIck method actually fires the function by displaying an alert().

So, that let me to believe that I am dealing with something related to the single treat in JS. If someone with more expertise and knowledge could guide me on this matter I would appreciated a lot. This is my code:

//component that starts timer

const startTimer = (sitNumber)=>{
   
    
   const id = setInterval(async()=>{

            updateSec = updateSec -1
           
            console.log('updateSec', updateSec)
            console.log('minutes', time.m)

            if(updateSec === 0){
                updateMin = updateMin -1
                updateSec = 60
            }

            if(time.m <= 0 || updateMin <= 0){

                clearInterval(id)
                const response = await fetch('http://localhost:3005/dashboard/unblocksit', {
                    method : 'PUT',
                    headers:{'content-type':'application/json'},
                    body :JSON.stringify({flightName : flight.flightName, sit : sitNumber })  
                    
                })
                const parseResponse =await  response.json() 
                setCount2(count+1)
                setShowCheckOut(false)
                setTime({s:60, m :4})
                console.log('this is the unblock response', parseResponse)
                
            }
            return setTime({s : updateSec, m : updateMin})
            }, 1000) 
    
   

        
}

Keep in mind that while the above function is running every second for 4 minutes, the below function is fired with a click

//component that sends request to server

 const buyTicket = async(e)=>{
    e.preventDefault()
    // alert('button clicked') //it actually dsiplays the alert
    try {
        //In postman this url works properly
         const response = await fetch('http://localhost:3005/dashboard/buyticket',{
             
            method : 'POST',
            headers : {'content-type':'application/json'},
            body : JSON.stringify({
                flight: flight.flightName,
                sit : sit.sitNumber,
                price :  sit.price,
                origin : flight.origin,
                destination : flight.destination,
                passenger  })

        }
        
        )
        const parseResponse = response.json()
        console.log(parseResponse)
        setCount3(count3 +1)  

    } 
    catch (error) {

        console.log(error)
        
    }
}

    
    return(

        <div>
            <div className='timer'>
                <span>{time.m <= 0 ? time.m : "0" + time.m}</span> 
                <span>{time.s <= 0 ? time.s : "0" + time.s}</span> 

            </div>
             <div>
                 <form>

                     <label>Passenger full name</label>
                    <input 
                    type="text" 
                    value = {passenger}
                    onChange={e=>setPassenger(e.target.value)}
                    />

                     <button onClick={buyTicket}>Purchase</button>


                 </form>
            </div>
            
        </div>
       
    )

Finally, this is the server side:

buyTicket : async (req, res) =>{

        console.log('hello from buyticket controller')//I dont even get this console.log 
        const flight = req.body.flightName
        const sit = req.body.sitNumber
        const price = req.body.price
        const origin = req.body.origin
        const detination = req.body.destination
        const passenger = req.body.passenger

        const sitUnavailable = await Flight.findOneAndUpdate(

            {"flightName" : flight},
            {"$set" : {"sits.$[s].isAvailable" : false, "sits.$[s].isSuspended" : false}},
            {"arrayFilters" : [{"sits.sitNumber" : sit}], new : true}
            )

            return res.send(sitUnavailable)
    }

JavaScript Barcode detection API returning undefined for rawData

I would like to integrate a feature to my website which can detect QR codes. So for that, I had used Barcode Detection API. But it is returning undefined for rawData

<meta name="viewport" content="width=device-width"/>
<video id="bar" autoplay style="width:100vw;height:100vh;margin:0;object-fit:cover;"></video>
<canvas id="canvas1" hidden></canvas>
<img id="input" hidden/>
navigator.mediaDevices.getUserMedia({
    audio: 0,
    video: {
        facingMode: {
            exact: "environment"
        }
    }
}).then(s => {
    const bar = document.getElementById('bar');
    bar.srcObject = s;
    bar.onloadedmetadata = () => {
        setInterval(() => {
            const canvas = document.getElementById('canvas1');
            canvas.width = bar.videoWidth;
            canvas.height = bar.videoHeight;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(bar, 0, 0);
            const input = document.getElementById('input');
            input.src = canvas.toDataURL();
            if ('BarcodeDetector' in window) {
                const detector = new BarcodeDetector();
                detector.detect(input).then(detections => {
                    detections.forEach(detected => {
                        alert(detected.rawData)
                    })
                })
            }
        }, -1)
    }
});

Here is the demo: https://authentication-demo.000webhostapp.com/

__V8_EXCEPTION: Uncaught SyntaxError: Illegal return statement

I am using a CEF3 based browser.

It supports adding / evaluating code without having to define a function.

I also don’t have to state

"<script type = "text/javascript">

etc.

Instead, I can just pass a string to like this:

 Me.webkitx1.Eval(somestring)

It works fine.

Here is a code that I use to show the focus in the first found input element when the page has loaded.

Because “element” may also be null / empty / nothing, I have tried adding “return;” in one line.
However, since I do not define a function, it doesn’t allow me to use “return;”, I guess…

What could I do instead?

I would like to avoid using a bigger if-then-clause.

Thank you!

var element = document.querySelector("*[autofocus]");
if (element)
{
}
else
{
   element = document.querySelector("form input:not([type=hidden])");
}

if (element)
{
}
else
{
  return; // not working. The error is: "__V8_EXCEPTION:Uncaught SyntaxError: Illegal return statement"
}

element.selectionStart = element.selectionEnd = element.value.length;
element.focus();
var y = element.getBoundingClientRect().top + window.scrollY;
window.scroll(
{
   top: y,
   behavior: "smooth"
});

I run “npx cap run android” but get stuck at Deploying app-debug.apk to Pixel_3_API_31

I’m converting a React app to an android one. I run “npx cap run android” but get stuck at Deploying app-debug.apk to Pixel_3_API_31
another terminal opens and runs qemu-system-i386.exe, there is the following output, “[23376:18372:0619/124312.874:ERROR:broker_win.cc(55)] Error reading broker pipe: The pipe has been ended. (0x6D)”

npm --version 8.5.5
node --version 16.15.0
capacitor/cli: 3.6.0
capacitor/core: 3.6.0
capacitor/android: 3.6.0
capacitor/ios: 3.5.1

How to update the React State only after a return from API called is completed

basically what I want to do is to change a text that says “welcome” initially to “hello {user}, please check your email for verification” after the user has submitted a registration AND with a successful response from API that contains the above string.

However it seems the response variable is set to undefine before returning of the signup function (that posts and receives a return from an API call), and thus Setmessage is setting the message variable as undefined instead of the returned string that only comes after a few seconds later.

I have researched many methods about useEffect, call back function and AJAX knowledge, but I still don’t really understand what I need to do in my code.

export default function Signup() {
        const [message, Setmessage] = useState('Welcome')
        async function handleSubmit(e){
       
            const response = await signup(usernameRef.current.value, emailRef.current.value, passwordRef.current.value)
            Setmessage(response)
        }

        return(
        {message}
        //a submission form that invokes handlesubmit
        )
}

Javascript string regex replace with function callback behaves unexpected

I am currently lost in a javascript regex replace call.

This medium sized regex

/import +{ *(?<export>([a-zA-Z0-9]+,?)+) *} +from +"(?<file>(.{1,2}|([a-zA-Z0-9-_]+))((?=/)/[a-zA-Z0-9-_]+)*)"s*;/g

Should match import statements in javascript file.
For example

import {myFunc} from "./mylib";

This works when trying in this online tool (choosing the ECMA flavor)
at least on initial load if i change something in the input text it looses the match and undoing the change does not help.

The behaviour with actual javascript is similarly weird as
the regex does work if i call the replace with a simple string most of the time.
Somtimes i reload the script and it does not work with the same input.

let working = text.replace(regex, 'replaced');

But when providing a “replacer function” it never works.

let not_working = text.replace(regex,function (_, g){return 'replaced';});

And always returns the original string.

I looked into similar questions already
like this where resetting the regex was the issue.

Also using ‘$1’ to replace the capture groups didn’t work work me
as proposed here

The random nature of the behaviour made me think if this might be a catastrophic backtrack issue, but then the code would stop executing, wouldn’t it?
Also when the ‘regex101’ tool does find the match it only takes 0.6 ms,
which i think speaks against that.

Also an interesting note, it has to be tied to this specific regex as removing the last semicolon in it also makes it work 100% of the time.

/import +{ *(?<export>([a-zA-Z0-9]+,?)+) *} +from +"(?<file>(.{1,2}|([a-zA-Z0-9-_]+))((?=/)/[a-zA-Z0-9-_]+)*)"s*/g

I guess i could work with that, i just want to understand what leads to the described behaviour, to prevent future pitfalls.
Especially why the regex works in one function, but fails in another, which i thought should behave the same.

Example CodePen

Converts RGB values into Hex values without using toString(16)

I need my function to convert RGB decimal values into Hexadecimal values without using toString(16). This is what I have. Why isn’t it working? Is it because I have more than one switch statement so it completes the iteration without completing the second one?

function rgb(r, g, b){
 let result = '';
 // Convert into array for iteration
 let arr = [r,g,b];
 // Iterate through each color
 for(let i=0; i<arr.length; i++) {
  if (arr[i] > 255) result += 'FF';
  if (arr[i] < 0) result += '00';

 // Convert first iteration into hex format
  switch (Math.floor(arr[i]/16)) {
   case 10: result += 'A';break;
   case 11: result += 'B';break;
   case 12: result += 'C';break;
   case 13: result += 'D';break;
   case 14: result += 'E';break;
   case 15: result += 'F';break;
   default: result += (Math.floor(arr[i]/16) + '');
  }

 // Convert second iteration into hex format
  switch (((arr[i]/16)-16)*16) {
   case 10: result += 'A';break;
   case 11: result += 'B';break;
   case 12: result += 'C';break;
   case 13: result += 'D';break;
   case 14: result += 'E';break;
   case 15: result += 'F';break;
   default: result += ((((arr[i]/16)-16)*16) + '');
  }
 }
return result;
}

// function should return the following results.
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3

How can I run Javascript on Django without exposing static files?

On my Django site, I used Stripe to integrate payments in a .js file.

I noticed that this file appears under Sources in the developer tools when you “Inspect Element” on any browser. Anyone can access this file (scary).

How can I restructure my file organization so that apple-pay.js is not public facing?

home.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
    // Scripts for CSS and Stripe Pay
</head>
<body>
    <section>
        
       <div id="payment-request-button" data-amount="{{event.price}}" data-label=". 
          {{event.public_name}}">
                    <!-- A Stripe Element will be inserted here if the browser supports this type of payment method. -->
       </div>
       <div id="messages" role="alert"></div>

    </section>

</body>
</html>

apple-pay.js

document.addEventListener('DOMContentLoaded', async () => { 
    const stripe = Stripe('pk_mykeyishere'); //need to protect this information and the other functions from bad actors

    ///functions I run here
    
});

My file structure:

├── Procfile
├── README.md
├── db.sqlite3
├── interface
│   ├── migrations
│   ├── models.py
│   ├── static
│   │   ├── apple-developer-merchantid-domain-association
│   │   └── interface
│   │       ├── apple-pay.js <------------------
│   │       ├── CSS/other JS files
│   ├── templates
│   │   └── interface
│   │       ├── home.html <-------------------
│   ├── urls.py
│   └── views.py
├── manage.py
└── AppName
    ├── settings.py
    ├── urls.py
    └── wsgi.py