1

I'm currently working creating some communication between JS and Python using AJAX and Flask. To start off, the file structure is as follows:

-datacenters
   -app.py
   -index.html
   -index.js

I want to be able to send data back to index.html and display it without refreshing the page. The html invokes index.js, where I have used jQuery to perform an ajax POST to the locally running app.py.

index.js

function postData() {
  $.ajax({
      type: "POST",
      url: "http://127.0.0.1:5000/return_data/",
      success: function(resp) {
        alert(resp.data)
      }
  })
}

It's to my understanding that this function, when called, should access return_data located in app.py. I think it's doing so.

app.py

from flask import Flask, render_template, jsonify

app = Flask(__name__, template_folder='/Users/dcs/datacenters')
app.config['EXPLAIN_TEMPLATE_LOADING'] = True

.......

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

@app.route('/return_data/', methods=['POST'])
def return_data():
    values = [1, 2, 3]
    return jsonify({'data': render_template('index.html', values=values)})

if __name__ == "__main__":
    app.run(debug=True)

Each time postData is called, the output shown in app.py is:

[2019-12-31 10:18:25,890] INFO in debughelpers: Locating template "index.html":
    1: trying loader of application "__main__"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /Users/dcs/datacenters
       -> found ('/Users/dcs/datacenters/index.html')
127.0.0.1 - - [31/Dec/2019 10:18:25] "POST /return_data/ HTTP/1.1" 200 -

So the receiving part is fine, since it's giving 200. I know values is not used, I am simply trying to trigger an alert at this point before I move forward with any data manipulation.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MWray
  • 41
  • 2

0 Answers0