0

If I send data through render_template in server using Flask, how do I access it inside jQuery? I know how to do it in HTML but not in jQuery. The code I tried below doesn't work; the data variable is not being read at all. I need to use jQuery since I need to use the .append function to dynamically create the rows of questions and answers.

server:

from flask import request, Flask, render_template, send_from_directory
from flask_sqlalchemy import SQLAlchemy
import requests
import json
import jsonpickle

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'

db = SQLAlchemy(app)
class Tests(db.Model):
     id=db.Column(db.Integer, primary_key=True)
     question=db.Column(db.String(200),unique=True)
     answer = db.Column(db.String(200), unique=False)
     hint = db.Column(db.String(2000), unique=False)
     def __repr__(self):#Redefine what print(object) is
         return '{} {}'.format(self.question,self.answer)

@app.route('/dutch_training/<no>',methods=['GET','POST'])
def dutch_training_les(no=0):
    data=Tests.query.get((no,no+1,no+2))
    return render_template("dutch_training.html",data=data)

dutch_training.html

{%extends "layout.html" %} {% block content %}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<script type="text/javascript">
  $(document).ready(function(){
        var i=0;
        data_parsed=jQuery.parseJSON(data);
        data_parsed.forEach(function(dt){
            var link_to_example="https://context.reverso.net/vertaling/nederlands-engels/"+ dt['question'];
            var link_to_hint = "/hint/" + dt['question']
            $("#all_questions").append("<p>"+ dt['id'] +". " + dt['question'] + " " +
                                        "<input id=\""+"question"+i+"\">" + "</input>" +
                                        "<button  style=\""+"height:20px;width:20px"+"\" type=\""+"radio"+"\" id=\""+i+"\">" + "</button>" +
                        '<a href="' + link_to_example + '">'+'Voorbeeldgebruik'+'</a>'+ '<br>' + '</br>' +
                                        '<a href="' + link_to_hint + '">'+'Eigen Hint'+'</a>'+"</p>");
            i++;
            });
        });
  });
</script>

<section class="page-section" style="background-color:lightblue" id="about">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8 text-center">
                <div class="inner" id="all_questions">
                </div>
            </div>
        </div>
    </div>

</section> {% endblock %}
aldo
  • 125
  • 1
  • 7
  • This question is already answered. https://stackoverflow.com/questions/11178426/how-can-i-pass-data-from-flask-to-javascript-in-a-template – pullam_vasant Sep 27 '20 at 19:44
  • JavaScript gets executed on the client side but you can initially render your data with `var data = {{ data }}` – Kruspe Sep 27 '20 at 19:45

1 Answers1

0

Just the same way you grab template data via HTML works for JS:

var data_parsed = '{{ data }}'
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18