I am encountering an issue with refreshing the page, specifically when I click the button that is meant to filter data using an ajax script. The problem arises when the IF condition does not work and prevents rendering of the template. Below is a snippet of the code:
Python
def viewchallenges():
categories = Categories.query.all()
if request.method=='POST':
category_id=Categories.query.filter_by(category=request.form['name']).first()
check=Challenge.query.filter_by(categorie_id=category_id.id).order_by(Challenge.timestamp.desc()).all()
if not check:
flash(_('not found'))
else:
page = request.args.get('page', 1, type=int)
posts = Challenge.query.filter_by(categorie_id=category_id.id).order_by(Challenge.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.viewchallenges', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.viewchallenges', page=posts.prev_num) \
if posts.has_prev else None
return render_template('viewChallanges.html', title=_('View Challenge'), posts=posts.items, next_url=next_url, prev_url=prev_url,categories=categories)
page = request.args.get('page', 1, type=int)
posts =Challenge.query.order_by(Challenge.timestamp.desc()).paginate(
page,current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.viewchallenges', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.viewchallenges', page=posts.prev_num) \
if posts.has_prev else None
return render_template('viewChallanges.html', title=_('View Challenge'), posts=posts.items, next_url=next_url, prev_url=prev_url,categories=categories)
HTML
{% for item_category in categories %}
<button class="btn btn-secondary fby_category">{{item_category.category}}</button>
{% endfor %}
AJAX
$('.fby_category').click(function(e) {
var url = "{{ url_for('main.viewchallenges') }}";
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: {
'name': $(this).text()
},
});
});