1

Currently, I am attempting to write the backend and front end of a program that records an array of information on every keypress and sends it to a Python backend. The Python backend then sends back a response (that will probably be a boolean) that the JavaScript responds to.

I believe I have figured out how to send an array to the Python back end via this video and this Stack Overflow post: https://www.youtube.com/watch?v=zJdQxS3ZpNI, Pass array to ajax request in $.ajax(). I have not yet worked out the exact processing; currently, I'm just following the tutorial to figure out what to do. As such, response function is just a placeholder.Below is the code that I have currently:

index.html:

<div id="response"></div>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>          
<script type="text/javascript">
  $.ajax({
    url: "/_get_data/",
    type: "POST",
    data: {data_array:data_array},
    success: function(resp){
      $('div/response').append(resp.data);
    }
  });
</script>
from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/_get_data/', methods=['POST'])
def _get_data():
  myList = ['Element1','Element2','Element3']

  return jsonify({'data': render_template('response.html',myList=myList)})

response.html:

<ul>
  {% for elem in myList %}
    <li>{{elem}}</li>
  {% endfor %}
</ul>

According to the tutorial, the line: return jsonify({'data': render_template('response.html',myList=myList)}) is the key. He said that the myList=myList part is the response, and 'data' and response.html is the data recieved. My question is, how do I access the data the JavaScript sent in my Python server, process it, then send it back in separate lines? I'm not really clear what "render_template" is doing, or how myList=myList works. Any explanations? Thanks!

davidism
  • 121,510
  • 29
  • 395
  • 339

1 Answers1

1

If you are using AJAX and sending an asynchronous call to flask, you might want to return a json object, to be consumed by the frontend, as opposed to an html template.

To you question, you can access the form passed to your request using

myData = request.get_json() #if json
myForm = request.form #if form data

And change the response to a json object only:

@app.route('/_get_data/', methods=['POST'])
def _get_data():

  myList = ['Element1','Element2','Element3']

  # get data:
  myData = request.get_json()

  ## do something with data

  return jsonify({'data': myList}) #return a json object, that can be used by your AJAX call.

Additionally you can use make_response to generate your response, together with the desired status code:

from flask import make_response

# ...

@app.route('/_get_data/', methods=['POST'])
def _get_data():

  myList = ['Element1','Element2','Element3']

  myData = request.get_json()

  ## do something with data

  ## if something is wrong
      ## return make_response(jsonify({'Error': 'Error Msg'}), 400)

  return make_response(jsonify({'data': myList}),200)


Just make sure to pass the request content type to application/json to prevent from unexpected behavior when reading the data (see this answer )

realr
  • 3,652
  • 6
  • 23
  • 34