javascripthtmlflaskflask-socketio

How do I pass a JavaScript variable to Flask?


I'm relatively new to JavaScript. I have a function in flask which I want to call, but it requires arguments which can only be defined in JavaScript.

var socket = io();
socket.connect('http://127.0.0.1:5000/');
socket.on('connect', function() {
    console.log('connected')
});

function createSpan() {
    var c = 1
    for (let i of document.getElementsByTagName('li')) {
        var span = document.createElement('span');
        span.id = 'outlineSpan'
        var clonedLI = i.cloneNode(true);
        span.appendChild(clonedLI);
        console.log(i.innerHTML)
        var genNotesBtn = document.createElement('button');
        genNotesBtn.className = 'genNotesBtn';
        genNotesBtn.id = 'genNotesBtn' + c;
        c++;
        genNotesBtn.innerHTML = 'Generate notes.';
        genNotesBtn.onclick = function() {
            socket.emit('notesGen')
        }
        span.appendChild(genNotesBtn);
        i.parentNode.replaceChild(span, i);
        var text = i.innerHTML;
    }
}

How can I use text as the variable for subheading in this SocketIO function:

@socketio.on('notesGen')
def notesGen():
    assistantID = notesGenAssistant()
    subheading = ?
    notesGenThread(subheading, detail)
    notesGenRun(notesGenAssistantID, threadid)

I tried to redeclare var text = i.innerHTML; to var text = '{{ subheading }}', but Flask didn't recognise the variable.


Solution

  • In the client, send your data in the emit() call:

            genNotesBtn.onclick = function() {
                socket.emit('notesGen', '<send what you want here>')
            }
    

    Then in the server add an argument to your handler:

    @socketio.on('notesGen')
    def notesGen(data):
        # data is what the client sent