I've been learning flask. i've also created two projects in it. It's my third project. I'm always stuck on this point. I want to make server side code run when a event happens on page say, a button is clicked.
In the linked image. I want the entry be deleted when 'delete' button is clicked. I've holding the data on mysql server, so I want it to be deleted from there as well
Here is what I have done. I created a route /delete_student
and it handles deleting the student.
But the problem is it's always reloading the page and also It switches to different url. I don't want any of them to happen. What should I do? Should I use Ajax, if yes, please tell me, how?
HTML
{% for i in data %}
<tr>
<td>{{i['roll_no']}}</td>
<td>{{i['name']}}</td>
<td>{{i['username']}}</td>
<td>{{i['password']}}</td>
<td><a href="#">Edit</a></td>
<td><a href="{{url_for('delete_student')}}">Delete</a></td>
</tr>
{% endfor %}
Flask
@app.route('/delete_student')
@is_logged_in
def delete_student():
if session['username']=='nitti':
cur = mysql.connection.cursor()
#pop the row from the table?
#how to identify the row being deleted?
return render_template(url_for('student_summary'))
You should access the route with javascript.
Checkout AJAX with jQuery:
http://flask.pocoo.org/docs/0.12/patterns/jquery/
For example, if you have a button that says "Delete Student":
@app.route("/_delete_student")
def delete_student():
student_id = request.form.get("student_id")
cur = mysql.connection.cursor()
cur.execute("DELETE FROM students WHERE student_id = %s", (student_id,)
conn.commit()
return jsonify(status="success")
JavaScript:
$("#delete_student").click(function(){
$.ajax({
type: 'POST',
url: "/_delete_student",
data: {student_id: 1},
dataType: "text",
success: function(data){
alert("Deleted Student ID "+ student_id.toString());
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With