0

I'm trying to create a chat app using Flask and JavaScript, but I'm running into a problem. I used jQuery to accept the username and message, and Flask to put the message on the page. Is there anyway I can do this in real-time, and without reloading the page?

(to collect data and convert to JSON)

$(function () {
    $('#send').bind('click', function () {
        $.getJSON('/send', {
            user: $('#username').val(),
            mess: $('#message').val()
        }, function (data) {
            console.log('message sent')
            //$("#result").append(data.result + '<br>');
        });
        return false;
    });
});

(app.py)

messages = []
@app.route('/')
def index():
    return render_template('index.html', messages=messages)

@app.route('/send',)
def send():
    try:
        username = request.args.get('user')
        message = request.args.get('mess')
        messages.append([username, message])
        return jsonify(result=username + ': ' + message + '; ')
    except Exception as e:
        return e

1 Answer 1

4

There is. However, not in your current setup. The HTTP standard, which Flask uses only returns data when it is called. So only when you call the '/' route in your flask app it will return data. The easy solution is to call every 5 seconds to see if there are changes. This can be implemented with the JavaScript setInterval function.

The other option that you have is to start using websockets with the socketio library. You can connect Flask with this library through the flask-socketio extension.

Find information below:

https://socket.io/

https://flask-socketio.readthedocs.io/en/latest/

Obviously, these are not the only solutions. There are more ways to get what you want. However, explaining this would be more complicated and I think that with these two options you can already implement something.

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.