1

Completely new to Python and Flask. Trying to read from database and pass the data to Javascript. Pulling my hair out trying to get it working, as I assume it's something small

In my python script I have:

@app.route('/report')
def test():
    db = get_db()
    cur = db.execute('select * from emails where id=1')
    emails = cur.fetchall()
    print emails
    return render_template('report.html', name=links, emails=emails)

and then in my javascript I have:

{% for entry in emails %}
    var getEmail = {{entry.1}}
    window.alert(getEmail);
    emailArray.push(getEmail)
{% endfor %}

print emails is outputting [(1, u'e')], which is correct, but the window.alert is giving me "undefined". If I change it to var getEmail = {{entry.0}} it gives me the correct ID value from the database. Can anyone point me to where I'm going wrong?

1 Answer 1

3

You are generating:

var getEmail = e;

which is not working since e is undefined.

You want to quote your variables; use the tojson filter which comes with Flask, together with safe (to keep from quoting the " quotes generated):

var getEmail = {{ entry.1|tojson|safe }};

which will generate valid JSON, which is a subset of Javascript. Now your line will read:

var getEmail = "e";

Alternatively, set the emailArray list in one go (no loop over emails required) with:

var emailArray = {{ emails|map(attribute=1)|list|tojson|safe }};

which would take your emails list, select the 2nd element of each tuple, and output the resulting list as a JSON list, resulting in:

var emailArray = ["e"];
Sign up to request clarification or add additional context in comments.

2 Comments

That worked great! Thanks so much. Am I correct in saying that this doesn't apply to getting integer values? I was using pretty much the exact same code in a different spot to pull an integer value from my database and it worked fine, or should I use the tojson regardless of the datatype I'm retrieving?
@Killian: it so happens that the representation of integers is the same in both Python and Javascript, and that the string version of integers looks exactly like the literal value of an integer. In other words "1" in a template looks exactly like 1, which is fine for JavaScript. For strings this doesn't work, you need those quotes. Best bet is to just use tojson everywhere you need set JavaScript literals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.