How to send data from JavaScript to Python(flask)?

I am building a webpage where there is an input box in which the user types and while the user is typing I want to send the data o flask. I know I can use onkeyup in JS but I don’t know how to send this value to flask. Any help.

You’d send an XMLHttpRequest for this (or use the fetch API if you prefer). It works like this: in your flask app you define a route to handle the user input, e.g.

@app.route('/api', methods = ['POST'])
def api():
  # Do something useful here...
  return request.values.get('input', '')

This will simply respond with the input value it receives; the JS would then listen to keyup events and send the current value to the server:

const API_URL = '/api'
const input = document.getElementById('my-input')

const handleResponse = ({ target }) => {
  // Do something useful here...

const handleInput = ({ target }) => {
  const xhr = new XMLHttpRequest()
  const data = new FormData()

  data.append('input', target.value)
  xhr.addEventListener('load', handleResponse)'POST', API_URL)

input.addEventListener('keyup', handleInput)

This is of course not particularly useful so far, but you get the idea. :-) And unless you want to track each and every keystroke, you might also have a look at throttling to reduce the number of requests.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.