I'm developing a web application with Python, Flask and Mysql. In order to refresh the data without having to refresh the page, I made an api endpoint that returns all data in JSON format and then I populate it on an html page with AJAX, but it's not working.
Here's the code: *API that returns JSON
@app.route('/api/all_posts')
def get_all_posts():
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM lost_pets')
lost = list(cursor.fetchall())
cursor.execute('SELECT * FROM found_pets')
found = list(cursor.fetchall())
cursor.close()
return jsonify({"lost": lost, "found": found})
The JSON looks something like this:
{
"found": [
{
"barrio": "Centro",
"calle_1": "Av. Uruguay",
"calle_2": "Ejido",
"created_at": "2022-02-27 15:37:19",
"fecha": "Sun, 27 Feb 2022 00:00:00 GMT",
"foto": "e932de86-4e1a-4a3a-9dc1-2d13059182c7.jpg",
"hora": "12:37",
"id": "found1db9dc00-cea1-4e8e-bb40-c0f91012401d",
"mascota": "gato"
}
],
"lost": [
{
"barrio": "Tres Cruces",
"calle_1": "Bulevar Artigas",
"calle_2": "Av. Italia",
"created_at": "2022-02-27 00:53:55",
"fecha": "Wed, 16 Feb 2022 00:00:00 GMT",
"foto": "2d3c7c2f-7d4f-49b6-bb1b-e8a329148668.jpg",
"hora": "15:59",
"id": "lost4bfe723a-ab6b-4818-b9d3-a34a72f93ee2",
"mascota": "perro",
"nombre": "Señor M"
}
]
}
*Route to HTML file
@app.route('/landing')
def landing():
return render_template('index2.html')
*HTML file
{% extends "base.html" %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='styles/index.css') }}">
<title>EncuentraMe</title>
{% endblock %}
{% block body %}
<div class="feed">
<div class="filters">
<div class="filter">
<button type="button" class="btn btn-success btn-sm" id="all" onclick="refreshFeed()">Todos</button>
<button type="button" class="btn btn-outline-success btn-sm" id="lost">Perdidos</button>
<button type="button" class="btn btn-outline-success btn-sm" id="found">Encontrados</button>
</div>
<div class="post">
<a href="lost_pet" target="_blank" class="btn btn-primary" role="button">Publicar</a>
</div>
</div>
<article class="posts">
</article>
</div>
<script src="{{ url_for('static', filename='js/index.js') }}"></script>
<script src="{{ url_for('static', filename='js/populate.js') }}"></script>
{% endblock %}
*And Finally, the AJAX code
$(document).ready(function () {
async function fetchAllPosts() {
const response = await fetch('http://localhost:5000/api/all_posts');
const data = await response.json();
return (data);
}
async function refreshFeed() {
fetchAllPosts().then(function (data) {
$.each(data.lost, function () {
let postLostNew = $(document.createElement('div'));
postLostNew.attr('id', 'lost');
postLostNew.addClass('pet');
postLostNew.addClass('pet_lost');
postLostNew.append('<p>¡Se busca a ' + this.nombre + '! Perdido/a desde el día '
+ this.fecha + ' última vez visto en las inmediaciones de ' + this.calle_1 +
' y ' + this.calle_2 + ' barrio ' + this.barrio + ' a las ' + this.hora + ' horas.\n'
+ 'Si lo viste por favor comunícate con Usuario.</p>');
postLostNew.append('<a href="/' + this.id + '"></a>');
postLostNew.find('a').append('<img src="static/images/' + this.foto + '">');
$('article.posts').append(postLostNew);
});
$.each(data.found, function () {
let postFoundNew = $(document.createElement('div'));
postFoundNew.attr('id', 'found');
postFoundNew.addClass('pet');
postFoundNew.addClass('pet_found');
postFoundNew.append('<p>Se encontró el día ' + this.fecha + ' por barrio '
+ this.barrio + ' en las inmediaciones de ' + this.calle_1 +
' y ' + this.calle_2 + ' a las ' + this.hora + ' horas.\n'
+ 'Si es tuyo o sabes de quien puede ser por favor comunícate con Usuario.</p>');
postFoundNew.append('<a href="/' + this.id + '"></a>');
postFoundNew.find('a').append('<img src="static/images/' + this.foto + '">');
$('article.posts').append(postFoundNew);
});
});
}
refreshFeed();
});
The data is populating just fine, the thing is, when I press the button "Todos" it should fetch the JSON API and refresh the data inside the feed without having to refresh the page. But it does nothing.
Let me know if you need any other piece of my code.