Skip to content
Advertisement

How to get the position data from the joystick to the flask server?

I would like to get the position data from the js joystick o use it at the flask server. I tried using ajax:

python:

@app.route(‘/test’, methods=[‘GET’, ‘POST’]) def test_ajax():

    if request.method == "POST":
        data = request.json
        print('data:', data)
        result = {'url': url_for('index')}
        print('result:', result)
        return jsonify(result)
    else:
        return render_template('index.html')

<div class="container fluid">
    
            <h1>Joystick</h1>
            
            <div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>
    
        </div>
        
        <script type="text/javascript">
                   
          var Joy1 = new JoyStick('joy1Div', {}, function(stickData) {
          joy1IinputPosX.value = stickData.xPosition;
          joy1InputPosY.value = stickData.yPosition;
          joy1Direzione.value = stickData.cardinalDirection;
          joy1X.value = stickData.x;
          joy1Y.value = stickData.y;
          });
            
        </script>
    
        <script>
    
          data = {'ID': 'foobar'};
          var joystick = document.getElementById('joy1Div');
          joy1X.onchange = function() {
            $.ajax({
              type: "POST",
              url: "/test",
              contentType: 'application/json;charset=UTF-8',
              data: JSON.stringify(data, null, 't'),
              dataType: 'json',
              success: function(data) {
                  window.location.href = data['url']
              },
              error: function(response) {
                  alert(response)
              },
          });
          }; 
    
        </script> 

Every time the position of the joystick changed I would like to send the position data to flask

Advertisement

Answer

You can simply use the callback function to send the joystick data. In this example I use fetch to transfer the data via AJAX.

from flask import Flask
from flask import (
    jsonify,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process', methods=['POST'])
def process():
    data = request.get_json()
    print(data)
    return jsonify(message='Success', stickdata=data)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>

    <script type="text/javascript" src="{{ url_for('static', filename='js/joy.min.js') }}"></script>
    <script type="text/javascript">
      (function() {
        const joy1 = new JoyStick('joy1Div', {}, function(stickData) {
          fetch('/process', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(stickData)
          }).then(resp => resp.json())
            .then(data => console.log(data));
        });
      })();
    </script>
  </body>
</html>

If you accept the legitimate suggestion of using websockets, I would recommend Flask-SocketIO.

from flask import Flask
from flask import render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.secret_key = 'your secret here'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('stick')
def handle_stick(data):
    print(data)

if __name__ == '__main__':
    socketio.run(app)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>

    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/joy.min.js') }}"></script>
    <script type="text/javascript">
      (function() {
        const sock = io();
        const joy1 = new JoyStick('joy1Div', {}, function(stickData) {
          sock.emit('stick', stickData);
        });
      })();
    </script>

  </body>
</html>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement