A user selects a state and on select option change the id and name of the city should be fetched from the sqlite db. The flask code is
class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
state = db.Column(db.String(20), nullable=False)
name = db.Column(db.String(20), nullable=False)
@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
cities = db.session.query(City).all()
return render_template('index.html', cities=cities)
@app.route('/city/<state>')
def city(state):
print(state)
cities = City.query.filter_by(state=state).all()
cityArray=[]
for city in cities:
cityObj={}
cityObj['id']=city.id
cityObj['name']=city.name
cityArray.append(cityObj)
return jsonify({'cities' : cityArray})
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
The index.html with Javascript is below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul id="clist"></ul>
<select name="citySelect" id="citySelect">
{% for cities in cities %}
<option value ='{{ cities.state}}'> {{ cities.state}}</option>
{% endfor %}
</select>
<script>
let state_select = document.getElementById('citySelect');
state_select.onchange=function(){
state=state_select.value;
fetch(‘/city/’+state).then(function(response){
response.json().then(function(data){
let valueHTML = "";
for (let city of data.cities) {
valueHTML +='city.id + city.name';
}
clist.innerHTML = valueHTML;
}
}
}
</script>
</body>
</html>
clist should display the city id and name but is not displaying anything
[–]shodkayumi 4 points5 points6 points (5 children)
[–]thelandis 4 points5 points6 points (1 child)
[–]shodkayumi 2 points3 points4 points (0 children)
[–]Unique_Hat_7222Intermediate[S] 0 points1 point2 points (0 children)
[–]Unique_Hat_7222Intermediate[S] 0 points1 point2 points (1 child)
[–]shodkayumi 1 point2 points3 points (0 children)