Pass JS variable to another JS and to django view

I have several cards with items.
I added a counter to each card and a button ‘Add to cart’.
I want to pass the count of item into django view using ajax.
But I dont know how to pass variable from counter to ajax function, for each card.
The current version doesn’t work correctly, cuz every time count = 1.

var globalVariable;
var buttonPlus = $(".qty-btn-plus");
var buttonMinus = $(".qty-btn-minus");
var incrementPlus = buttonPlus.click(function() {
  var $n = $(this)
  .parent(".col")
  .find(".input-qty");
  $n.val(Number($n.val()) + 1);
  globalVariable = $(this).$n.val();
});

var incrementMinus = buttonMinus.click(function() {
  var $n = $(this)
  .parent(".col")
  .find(".input-qty");
  var amount = Number($n.val());
  1
  if (amount > 0) {
    $n.val(amount - 1);
    globalVariable = $(this).$n.val();
  }
});

$(document).ready(function() {
  $(".send-quantity").click(function() {
    var quantity = globalVariable;

    if (quantity === undefined) {
      quantity = 1;
    }
    var id = $(this).data("id");
    $.ajax({
      url: "{% url 'stripe_order:cart_add' %}",
      data: {
        'id': id,
        'quantity': quantity,
      },
    });
  });
});

My HTML:

{% for item in items %}
      <div class="col">
        <div class="card mb-4 rounded-4 shadow-sm">
          <div class="card-header py-3">
            <h3 class="my-0 fw-normal">{{ item.name }}</h3>
          </div>
          <div class="card-body">
            <h4 class="card-title pricing-card-title ">${{ item.price }}</h4>
            <ul class="list-unstyled mt-3 mb-4">
              <li>{{ item.description }}</li>
            </ul>
              <div class="row">
                <div class="col">
                  <div class="col input-group input-group-sm mb-3">
                      <button class="qty-btn-minus w-10 btn btn-outline-primary btn-sm" type="button"><i class="fa fa-minus"></i></button>
                      <input type="text" name="qty" value="1" class="input-qty form-control">
                      <button class="qty-btn-plus w-10 btn btn-outline-primary btn-sm" type="button"><i class="fa fa-plus"></i></button>
                  </div>
                </div>
                  <div class="col">
            <a data-id="{{ item.id}}" type="button" class="w-10 btn btn-outline-primary btn-sm send-quantity">Add to cart</a>
         </div>
          </div>
              </div>
        </div>
      </div>
    {% endfor %}

THX!

I need to create a backend project project within a month. So someone just a idea please [closed]

I learned SQL and I know basics in js, html/css, python,c#
I need to learn and create a backend project immediately within a month.
So someone just me idea, with what programming language to learn please.

I want to learn quick and implement it in as a project for an admission and it would be better if interviewers like that.So someone suggest me a simple and effective plan for that and I’m ready to give my everything into that project.

Is there a way to implant a loop variable into a variable?

I’m trying to do a loop that makes my life easier for this tic-tac-toe game, and instead of writing out every single variable I’d thought there might be a way to use a loop. I am a beginner and I’m trying to learn more.

const board = [
    "", "", "",

    "", "", "",

    "", "", "" 
];

// 0 = X, 1 = O

const turn = 0;

const reset = document.getElementById('reset');
const button1 = document.getElementById("1");
const button2 = document.getElementById("2");
const button3 = document.getElementById("3");
const button4 = document.getElementById("4");
const button5 = document.getElementById("5");
const button6 = document.getElementById("6");
const button7 = document.getElementById("7");
const button8 = document.getElementById("8");
const button9 = document.getElementById("9");

reset.addEventListener('click', () => {
    board = [
        "", "", "",
    
        "", "", "",
    
        "", "", "" 
    ];
})

setInterval(() => {
    // loop in here
}, 100);

How to deal with a HTTP POST method status code 404 (Not Found)?

am running some docker containers inside a virtual machine. As I come to understand, each docker container has a different ip, as well as the virtual machine itself of course. When trying to run a web-app on my local host machine, I access the page http://<vm’s_ip_address>:3000.

When attempting to execute an action in this web app, the following error occurs:
POST http://83.212.117.117/websites/evaluate 404 (Not Found)

The error happens on the handleSubmit(event) method of the following ResultPageDisplay file:

`handleSubmit(event) {
event.preventDefault()

this.setState({statusCode: 2})

API.post(`websites/evaluate`, { url: this.state.userInput})
  .then(res => {
     let score = res.data.score
     let url = res.data.url
     let imageURI = res.data.image

     // DEBUGGING PURPOSES
     // console.log(res.data)

     this.setState({result: {
       score: score,
       url: url,
       imageURI: imageURI
     }})
     this.setState({statusCode: 3})
  })
  .catch(err => {
    let failedURL = this.state.userInput
    this.setState({result: {
      score: null,
      url: failedURL,
      imageURI: null
    }})
    let status = err.response.status

    // DEBUGGING PURPOSES
    // console.log(status)

    this.setState({statusCode: 4})

    if (status === 500) {
      this.setState({
        statusCode: 5
      })
    }

  })

}`

I am suspecting that the problem lies somewhere in the configuration files, like nginx.conf. I am also wondering if there is something wrong with some other file like server.js or api.js.

I tried modifying these files, by creating a reverse proxy to map the ports correctly, but I do not understand the whole concept pretty well and maybe I was doing it not correctly. My nginx.conf file is the following:

`upstream app {
    server client:3000;
}

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}`

How come TypeScript does not narrow this index signature?

Consider this index signature type with a union as the value:

type Foo = { [key: string]: number | { [key: string]: number } }[];

If we try to narrow it:

const foo = (arr: Foo, outer: string, inner: string) => {
  arr.forEach((element) => {
    if(typeof element[outer] === 'number') {
      // element[outer] is a number
    }
    else if(!element[outer]) {
      // element[outer] is falsy (e.g. undefined)
    }
    else {
      // Here, TS should know that element[outer] is a well defined object
      console.log(element[outer]?.[inner]);
    }
  });
};

We get the following error message on element[outer]?.[inner]:

Element implicitly has an ‘any’ type because expression of type
‘string’ can’t be used to index type ‘number | { [key: string]:
number; }’.

No index signature with a parameter of type ‘string’ was found on
type ‘number | { [key: string]: number; }’.ts(7053)

Here is a similar example from the docs, where narrowing works:

function padLeft(padding: number | string, input: string): string {
  if (typeof padding === "number") {
    return " ".repeat(padding) + input;
  }
  return padding + input;
}

How come the narrowing does not work in the first snippet above?


EDIT:

One solution is to assign the element to another variable. I do not understand why that works, or why it is necessary. In the docs example above, we did not have to re-assign the function parameter that we narrowed.

Works:

const foo2 = (arr: Foo, outer: string, inner: string) => {
  arr.forEach((element) => {
    const outerValue = element[outer]; // The key!
    if(typeof outerValue === 'number') {
      // element[outer] is a number
    }
    else if(!outerValue) {
      // element[outer] is falsy (e.g. undefined)
    }
    else {
      // Here, TS should know that element[outer] is a well defined object
      console.log(outerValue[inner]);
    }
  });
};

How to Get Values Back in HYPER TERMINAL

I have write a HTML code for a sign up page now I want that which values I have entered in my browser in email and password box,it must be show in hyper terminal but its not working

Its just showing In hyper terminal that server running on port 3000

How to render a chart with dynamic data using handlebars?

In the below code I try to pass the dynamic data like mentioned, but its throwing an error.I have added the code written in handlebars below.When add statically its working but passing dynamically its not working throwing Missing helper JSON.stringify

    const data = {{{JSON.stringify data}}};
    // Extracting labels and navData from data
    const labels = data.map(item => item.date);
    const navData = data.map(item => item.nav);
     
      Error message:

     "message": {
  "message": "Missing helper: "JSON.stringify"",
  "name": "Error"
},

This is the code written in handlebars, By using this chart need to rendered in pdf .Please help me resolve the issue

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Report</title>
    <link rel="stylesheet" href="/stylesheets/style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
</head>
<style>
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }

    table {
        width: 100%
    }

    td {
        text-align: center
    }
</style>

<body>
    <div><br/></div>
    <div class="invoice-box">
        <table style="width:100%">
            <tr style="width:100%">
                <th>NAV</th>
                <th>Date</th>
            </tr>
            {{#each data}}
            <tr class="item {{#if @last}} last {{/if}}" style="width:100%;text-align:center">
                <td style='font-family: sans-serif'>{{this.nav}}</td>
                <td>{{this.date}}</td>
            </tr>
            {{/each}}
        </table>
    </div>
    <canvas id="canvas" style="width:90vw"></canvas>
    <script>
        // Get data from the server or wherever it's available
        const data = {{{JSON.stringify data}}};

        // Extracting labels and navData from data
        const labels = data.map(item => item.date);
        const navData = data.map(item => item.nav);

        // Chart data
        const chartData = {
            labels: labels,
            datasets: [{
                label: "NAV_HISTORY",
                type: 'line',
                data: navData,
                backgroundColor: 'transparent',
                borderColor: 'blue',
                borderWidth: 1,
                lineTension: 0,
                pointBackgroundColor: 'blue',
            }]
        };

        // Chart initialization
        const ctx = document.getElementById('canvas').getContext('2d');
        const chart = new Chart(ctx, {
            type: 'line',
            data: chartData,
            options: {
                responsive: false,
                animation: false,
                maintainAspectRatio: false,
                devicePixelRatio: 1,
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }],
                    xAxes: [{
                        ticks: {
                            autoSkip: true,
                            maxTicksLimit: 10,
                            maxRotation: 0,
                            minRotation: 0
                        }
                    }]
                }
            }
        });
    </script>
</body>

</html>

Is it OK to use the same Redux store for multiple Providers in different react Roots?

I am writing a web extension which extends the UI of a pre-existing website without having any control over it.

I would like to use Redux to manage the state of my app because it is starting to be way too messy.

I need to modify several unrelated parts of the default UI of the website, so I will need multiple, un-nested React Roots. That means as many StoreProviders too.

Is it OK to have multiple StoreProviders using the same Redux store instance?

How to generate new page in the same tab with JavaScript?

On the HTML page I have some anchor elements and click eventListner for every anchor like this:

<a href="letters/1" class="letter">
    <span class="letter-title">Title</span>
    <span class="letter-text">Text</span>
</a>

The thing is there’s no such page as “/letters/1” or even “/letters” because I want to make it dynamically, generate depending on which ‘a’ tag gets clicked either letters/1 or letters/2 and etc. I know how I would generate HTML code of the newly created page. For that purpose I have letter.html which inner HTML holds the template and is going to be modified to display a letter. What I don’t know is:

  1. Is it possible to makeup the url to look like “/letters/1” instead of “/letter.html”?

  2. I’ve tried to make click event on anchor do a redirect to the letter.html but only managed to open this page in another tab. When I try to override the redirection in click event it still tries to open “letters/1” even though function returns false as suggested in other questions on this site.

    let letterItems = document.querySelectorAll('.letter');
    
     letterItems.forEach(n => n.addEventListener("click", () => {
         window.location = './letters.html'
         return false
     }))
    

The above doesn’t work, and I also tried to use ‘window.location.replace’ or assign. For some reason only the ‘window.open()’ worked.

My other guess is since we already have every letter on the page and it’s title and text we can on anchor click event replace the whole HTML with letter content but doesn’t seem elegant and still I don’t know how to prevent going to “letters/1” and it doesn’t answer the question 1)

Frida il2cppbridge access violation when trying method Add or Insert at System.Collections.Generic.List`1 (List)

Why I’m getting always access violation error when trying to add values to generic list or what I’m doing wrong?

let list = Il2Cpp.corlib.class("System.Collections.Generic.List`1")
let int = Il2Cpp.corlib.class("System.Int32")
let listInt = list.inflate(int).new()
                     
listInt.method(".ctor").invoke()
listInt.method("Add").invoke(1)

or also if I get the list from internal like:

// return type is List<int>
let list = anyClass.method<Il2Cpp.Object>("getList").invoke()
                     

list.method("Add").invoke(1)

Getting always the same error, doesn’t matter if I try method “Add”, “Insert” or “set_Item”

Error: access violation accessing 0x3e8
at invokeRaw (il2cpp/structs/method.ts:233)
at (src/index.ts:18)
at call (native)
at (il2cpp/structs/method.ts:354)

Methods like get_Count works fine.

Decrease time function

I have an error with the decreaseTime function. It’s built to hide a submit button and change the value of the input on the contact form for defined time.

On my old page it was running fine, but with JqueryMobile 1.4.5 it stops working. The name for the form is correct.

I hope somebody can help me. Thank you!

seconds = 20;

function decreaseTime() {
  document.contact.submit.value = seconds;
  seconds--;
  if (seconds < 0) {
    document.contact.submit.value = 'Submit';
    document.contact.submit.disabled = false;
    return true;
  }
  setTimeout('decreaseTime()', 2000);
}

window.onload = function() {
  document.contact.submit.value = seconds;
  setTimeout('decreaseTime()', 2000);
}

‘wheel’ event occurs when doesn’t touch the wheel

I have script like this, It shows the message in console when wheel works with ctrlkey(for mac command key)

const handleWheel = (e) =>{
    if (e.ctrlKey || e.metaKey){
        console.log("handle wheel is called");
    }
}

useEffect(() =>{
    ref_wrapper_div.current.addEventListener('wheel',handleWheel,{passive:false});
});

Now something strange happens.

  1. command with mouse wheel -> message appears
  2. release the wheel -> nothing happens
  3. push command key -> message appears

why this 3 happens?

How can I prevent this?

How to update specific items in an array of objects is Firebase?

I have a doc in firebase representing a class in schoold, which has a list of object items including array of objects:

{{students: [{
          id: "xxx",
          name: "John",
          weight: "55",
          isPassed: false
        },
        {
          id: "xxx",
          name: "Marley",
          weight: "44",
          isPassed: false
        },
        {
          id: "xxx",
          name: "Beth",
          weight: "48",
          isPassed: false
        },
        {
          id: "xxx",
          name: "David",
          weight: "58",
          isPassed: true
        },
      ]
    },
teachers: {{...}},
name: "Tigers"
}

I am trying to update all items having isPassed key to true. I need something like:

await updateDoc(doc(db,"classes", class.id), { 
        "students.isPassed": true   // I know this synthax is wrong
      })

How is this possible?

‘FormData’: parameter 1 is not of type ‘HTMLFormElement’, I am getting this error but i can’t fix it help pls

“your text`const authForm = useRef();
const handleSubmit = (e) => {

e.preventDefault();

//formData
let form = new FormData(authForm.current);
console.log(form)

}

This is the code of the form just to show you i did add the ref for authForm

            <form ref={authForm} className="w-[80%] max-w-[400px]">....</form>

I did try adding an id on the form and using the document.getElementbyID it still didnt work so help me pls.
I am not fully aware about the reason behind the error still so it would be appreciated if anyone can explain it as well.`

Why does transpiling with ESBuild won’t work with my express + ejs app?

I have the following file structure

.
├── package.json
├── public
│   ├── fonts
│   │   └── AppleColorEmoji.ttf
│   └── images
│       ├── favicon.ico
│       └── ico.svg
├── src
│   ├── application.js
│   ├── controllers
│   │   ├── event.controller.js
│   │   └── user.controller.js
│   ├── database.js
│   ├── index.js
│   ├── middlewares
│   │   ├── auth.middleware.js
│   │   └── error.middleware.js
│   ├── models
│   │   ├── event.model.js
│   │   ├── token.model.js
│   │   └── user.model.js
│   ├── routers
│   │   ├── index.js
│   │   └── user.router.js
│   ├── services
│   │   ├── auth.service.js
│   │   └── event.service.js
│   └── views
│       ├── pages
│       │   ├── 404.ejs
│       │   ├── events.ejs
│       │   ├── index.ejs
│       │   ├── login.ejs
│       │   └── submit.ejs
│       └── partials
│           ├── footer.ejs
│           ├── head.ejs
│           └── header.ejs
└── yarn.lock

and tried to use esbuild to ship this application (express + ejs) with the following command in package.json

...
"build": "esbuild src/index.js --platform=node --bundle --minify --outfile=dist/index.js",
...

this produces a single file index.js in a dist folder. The program runs but when I make any operacion to see the views. It throws a 500 http status. Do you guys know how to solve this issue?