I've looked through many topics on stackoverflow, github, Google and many more... and found many different answers although no simple answer.
I'm writing a Facebook game in JavaScript (using melonJS engine). The framework is Flask (Python).
What I am trying to do, is to have ability to send data between Python and JS code with no need to refresh the page (like database operations, email sending, etc.). I want the user just to see the game, choose options, play and the game does the rest.
While I have managed to see that something like below will work:
app.py
def add(f,l,a):
g.db.execute('insert into persons (fname,lname,age) values (?, ?, ?)',
[f,l,a])
g.db.commit()
@app.route('/')
def index():
cur = g.db.execute('select fname, lname, age from persons order by id desc')
entries = [dict(fname=row[0], lname=row[1], age=row[2]) for row in cur.fetchall()]
return render_template('app.html',entries=entries,addtodb=add)
app.html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>THE GAME</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.22" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var adddb = '{{addtodb('Anne','Monk','12')}}';
</script>
</head>
<body>
{{addtodb('Allie','Monk','78')}}
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.fname }} {{ entry.lname|safe }} </h2> Age: {{ entry.age }}</li>
{% else %}
<li><em>Unbelievable. No entries here so far</em></li>
{% endfor %}
</ul>
</body>
</html>
And both the {{addtodb}} will work. I just wonder how to send the function to file.js that will be only linked to the HTML (like jquery above), not put directly inside. The "{{...}}" will not work as I already checked. I suppose I have to find some module to Python or use AJAX maybe, except I have no idea where to start.