Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
Counting html button clicks in JS front end and sending it to flask backend

I am trying to track the number of times a button or a dropdown is clicked in my flask app and send it back to python backend so i can input into database. I keep getting null for my value i cant seem to figure it out.

new.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method = "POST">
        <button type="button" id = "numberclicks" name = "numberclicks" onClick="onClick()">Click me</button>
        <p>Clicks: <a id="clicks" name ="clicks" placeholder = 0 >{{clicks|safe}}</a></p>
        <button type="submit">Login</button>
    </form>
    </div>
    <script>
        var clicks = 0;
        function onClick() {
           clicks += 1;
           document.getElementById("clicks").innerHTML = clicks; 
           console.log(clicks)
        }   
        </script>

</body>
</html>

app.py

from flask import Flask,render_template,request

import json

app = Flask(__name__)



# turn this into calss and import to record who is logged in to the session aka. user then take log data and make relationship to tables
# HOW MANY TIMES USER VISITED THE VISIT PAGE!!! 



@app.route('/', methods=['POST', 'GET'])
def signUpUser():
    if request.method == "POST":
        click = request.args.get('clicks',type = int)
        return json.dumps({'status':'OK','click':click})
    return render_template("new.html")

if __name__ == "__main__":
    app.run(debug=True)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could use the XMLHttpRequest object to send the clicks count asychronously to the flask backend.

const xhr = new XMLHttpRequest();
xhr.open("POST", "/", true);
xhr.onload = () => {
    if (xhr.status === 200) {
        ...do whatever you want...
    }
}

const data = new FormData();
data.append("clicks", clicks);

xhr.send(data);
about 4 years ago · Juan Pablo Isaza Relatório

0

function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
  console.log(clicks);
  fetch("/", {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    method: "POST",
    body: JSON.stringify({clicks}),
  });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda