I am currently undertaking the Udacity Full Stack developer “degree” and it seems that the lesson on Ajax is incorrect (the code presented on the lesson does not work) and that is causing trouble to all students who take the course. Their help portal is filled with people questioning why the code wont work and it’s been over 1 year and Udacity has not provided an answer or corrected the material.
I am hoping to find an answer here to help all of the community.
The task is a simple to-do web app with a postgresql database behind it. Please see below for the code and view:
from xmlrpc.client import Boolean
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://antoniofurtado:abc@localhost:5432/todoapp'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class Todo(db.Model):
__tablename__='todos'
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(), nullable=False)
completed = db.Column(db.Boolean, nullable=False, default=False)
def __repr__(self):
return f'<todo {self.id} {self.description}>'
@app.route('/todos/create', methods=['POST'])
def create_todo():
description = request.get_json()['description']
todo = Todo(description=description)
db.session.add(todo)
db.session.commit()
return jsonify({
'description': todo.description
})
@app.route('/')
def index():
return render_template('index.html', data=Todo.query.all())
# FLASK-SETUP This code should be at the bottom of all your files.
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=3000)
The view related to the above code is:
<html>
<head>
<title>Todo App</title>
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<form>
<input type="text" id="description" name="description" />
<input type="submit" value="Create" />
</form>
<div id="error" class="hidden">Something went wrong!</div>
<ul>
{% for d in data %}
<li>{{ d.description }}</li>
{% endfor %}
</ul>
<script>
document.getElementById('form').onsubmit = function(e) {
e.preventDefault();
fetch('/todos/create', {
method: 'POST',
body: JSON.stringify({
'description': document.getElementById('description').value
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
console.log(jsonResponse);
const liItem = document.createElement('LI');
liItem.innerHTML = jsonResponse['description'];
document.getElementById('todos').appendChild(liItem);
document.getElementById('error').classname = 'hidden';
})
.catch(function() {
document.getElementById('error').classname = '';
})
}
</script>
</body>
</html>
When I add a new item to the todo list and hit the create button, the item is not added to the database and the page isn’t updated. All that happens is the URL changes to http://127.0.0.1:3000//?description=new+item and the terminal shows 127.0.0.1 - - [02/Mar/2022 00:37:57] "GET /?description=new+item HTTP/1.1" 200 -. The item is not added to the database or displayed on the page.
Can anyone see what the issue is? Any assistance would be hugely helpful to me but also to hundreds of Udacity students who can’t count on Udacity.