zxc
zxc

Reputation: 9

Return data from database using Flask, Flask-sqlalchemy, and jQuery

I want div.disp to get the id of the data to be added to the database, it works for the first add but for the next ones, it will be the same id as the the first add.

@app.route('/')
@app.route('/index')
def index():
    tsklst = models.User.query.order_by('id asc').all()
    last = tsklst[len(tsklst)-1].id+1
    return render_template('index.html',last=last)

@app.route('/_add')
def add_(): 
    toDo = request.args.get('task')
    u = models.User(task = str(toDo))
    db.session.add(u)
    db.session.commit()
    return render_template('index.html')

by my idea, div.disp should have an attribute id of the last+1 added data into the database

$(document).ready(function(){
    $('#btnTask').click(function(){
        if ($('#txtTask').val()!=''){
            $.getJSON('/_add',{
                task: $('#txtTask').val(),
            });
            $('.content').append("<div class='disp' id='{{ last }}'><div class='left'>"+$('#txtTask').val()+"</div><input type='checkbox' class='chkbk'></div>");
        }
        $('#txtTask').val('');
        $('#txtTask').focus();
    });
});

I'm currently looking at db.session.refresh() but I don't quite understand it

Upvotes: 0

Views: 1067

Answers (2)

zxc
zxc

Reputation: 9

my friend solved the problem for me:

content ="<div class='disp' id='"+str(u.id)+'><div class='left'>"+$('#txtTask').val()+"</div><input type='checkbox' class='chkbk'></div>"
return content

Upvotes: 0

Yumiko
Yumiko

Reputation: 468

It will be much better to return a json type object from _add endpoint rather than render a template

@app.route('/_add')
def add_(): 
    toDo = request.args.get('task')
    u = models.User(task = str(toDo))
    db.session.add(u)
    db.session.commit()
    task = {}
    task['id'] = u.id
    task['content'] = u.content
    return jsonify(task=task)

Upvotes: 1

Related Questions