snufsan snufsan - 1 year ago 82
Javascript Question

Trying to invoke python function from js using jQuery and Flask

I'm trying to design an interactive website for a presentation I'm making. I'm new at all this flask stuff, and I'm having some hard time understanding why my code doesnt work.

I'm trying to create a website, that every line in it is clickable, and on click I want to bind a python function that according to the text of the line do some calculation and replaces that text.
For that I have build a simple html:

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>click demo</title>

<p>2016-04-21 09:12:59</p>
<p>Second Paragraph</p>
<p>2016-04-21 09:12:59 bla bla</p>

<script src="//"></script>

$( "p" ).click(function() {
$.getJSON('/background_process', {
line: $(this).text(),
}, function(data) {
return false;



I also wrote flask code that should be binded once I click some line on my web page:

from flask import Flask, jsonify
app = Flask(__name__)
from flask import render_template
import re

def index():
return render_template('index.html')

def background_process():
lang = request.args.get('line', 0, type=str)
string = lang.split()[0]
if re.match(r'\d\d\d\d-\d\d-\d\d',string):
return jsonify(result=string)
return jsonify(result="Doesnt start with a date")
except Exception as e:
return str(e)
if __name__ == "__main__":

The problem is that the function does not work for some reason unless i'm specifying which spot to put the text by id of a slot in my html page, and I cant understand what went wrong.

Answer Source

You have two problems in your app. The first one is that you are not importing the request module:

from flask import Flask, jsonify, request

Second, in your template, you are referring to this that is out of scope. This should work:

$( "p" ).click(function() {                                                                               
  var this_p = this;                                                                                      
  $.getJSON('/background_process', {                                                                      
        line: $(this_p).text(),                                                                           
    }, function(data) {                                                                                   
        return false;                                                                                     
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download