1

How do you send information from a client to a server? I kinda need to send some data from the client to server on a button click. Basically, I have this page where there are a couple of buttons, and I want to try to send information about each button (and some extra information about the status of the client, but that's not exactly necessary) to the server when it's pressed. The server should then process that information, and send a processed version to all connected clients.

It's crucial that the client does not refresh because then we would lose the data in the javascript game engine, and the user would have to start over.

Would ajax be appropriate? If it is, can someone include a short, generic example both with the javascript (client side) and Flask (server side) functions / code ?

1 Answer 1

2

Out of the box, you can't use persistent requests or websockets with something like Flask. However, you don't necessarily need this - you can use AJAX with a simple polling mechanism.

Client side:

$('button').click(function() {
    var state = $(this).attr('data-state');

    $.post('/clients/', { state: state });
});

// Check for messages every 1 second
var checkDelay = 1000;
var lastMessageSeen = new Date().getTime();

setInterval(function() {
    $.get('/clients/', function(result) {
        if(result.ready and result.timestamp > lastMessageSeen) {
            lastMessageSeen = result.timestamp;
            console.log('Message received: ' + result.msg);
        }
    });
}, checkDelay);

Server side:

from flask import request, jsonify

@app.route('/clients/', methods=['POST'])
def client_broadcast():
    state = request.form['state']

    # here you can store the message under a key in Memcached, Redis or another in-memory cache server
    store_in_cache(state)

    return jsonify(stored=True)

@app.route('/clients/', methods=['GET'])
def client_retrieve():
    # retrieve messages from cache
    msg, timestamp = retrieve_from_cache()

    if msg:
        return jsonify(ready=True, msg=msg, timestamp=timestamp)
    else:
        return jsonify(ready=False)

I've left out the store_in_cache and retrieve_from_cache functions, because it depends on how you want to handle these messages. Are they global to all browser clients? Do you want to have a queue of messages?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.