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():
JavaScript
x
9
1
if request.method == "POST":
2
data = request.json
3
print('data:', data)
4
result = {'url': url_for('index')}
5
print('result:', result)
6
return jsonify(result)
7
else:
8
return render_template('index.html')
9
JavaScript
1
41
41
1
<div class="container fluid">
2
3
<h1>Joystick</h1>
4
5
<div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>
6
7
</div>
8
9
<script type="text/javascript">
10
11
var Joy1 = new JoyStick('joy1Div', {}, function(stickData) {
12
joy1IinputPosX.value = stickData.xPosition;
13
joy1InputPosY.value = stickData.yPosition;
14
joy1Direzione.value = stickData.cardinalDirection;
15
joy1X.value = stickData.x;
16
joy1Y.value = stickData.y;
17
});
18
19
</script>
20
21
<script>
22
23
data = {'ID': 'foobar'};
24
var joystick = document.getElementById('joy1Div');
25
joy1X.onchange = function() {
26
$.ajax({
27
type: "POST",
28
url: "/test",
29
contentType: 'application/json;charset=UTF-8',
30
data: JSON.stringify(data, null, 't'),
31
dataType: 'json',
32
success: function(data) {
33
window.location.href = data['url']
34
},
35
error: function(response) {
36
alert(response)
37
},
38
});
39
};
40
41
</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.
JavaScript
1
19
19
1
from flask import Flask
2
from flask import (
3
jsonify,
4
render_template,
5
request
6
)
7
8
app = Flask(__name__)
9
10
@app.route('/')
11
def index():
12
return render_template('index.html')
13
14
@app.route('/process', methods=['POST'])
15
def process():
16
data = request.get_json()
17
print(data)
18
return jsonify(message='Success', stickdata=data)
19
JavaScript
1
27
27
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title></title>
6
</head>
7
<body>
8
<div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>
9
10
<script type="text/javascript" src="{{ url_for('static', filename='js/joy.min.js') }}"></script>
11
<script type="text/javascript">
12
(function() {
13
const joy1 = new JoyStick('joy1Div', {}, function(stickData) {
14
fetch('/process', {
15
method: 'POST',
16
headers: {
17
'Content-Type': 'application/json'
18
},
19
body: JSON.stringify(stickData)
20
}).then(resp => resp.json())
21
.then(data => console.log(data));
22
});
23
})();
24
</script>
25
</body>
26
</html>
27
If you accept the legitimate suggestion of using websockets, I would recommend Flask-SocketIO.
JavaScript
1
19
19
1
from flask import Flask
2
from flask import render_template
3
from flask_socketio import SocketIO
4
5
app = Flask(__name__)
6
app.secret_key = 'your secret here'
7
socketio = SocketIO(app)
8
9
@app.route('/')
10
def index():
11
return render_template('index.html')
12
13
@socketio.on('stick')
14
def handle_stick(data):
15
print(data)
16
17
if __name__ == '__main__':
18
socketio.run(app)
19
JavaScript
1
23
23
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title></title>
6
</head>
7
<body>
8
<div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>
9
10
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
11
<script type="text/javascript" src="{{ url_for('static', filename='js/joy.min.js') }}"></script>
12
<script type="text/javascript">
13
(function() {
14
const sock = io();
15
const joy1 = new JoyStick('joy1Div', {}, function(stickData) {
16
sock.emit('stick', stickData);
17
});
18
})();
19
</script>
20
21
</body>
22
</html>
23