Issue
My issue is that whenever the button const loadOldPlayer
is clicked, it sends two GET requests, as shown in the screenshot below. What this results in is the wrong template being rendered (showsPlayer.html
should be what is rendered but instead it just renders playerView.html
). I can't figure out why this is happening, so any help is appreciated. Below the screenshot is my code.
let playerName
const loadOldPlayer = document.getElementById('playerLoader');
const enterProfile = (usedToLoad) => {
console.log(playerName)
if (usedToLoad) {
playerName = document.getElementById('loadPlayerName').value
};
const playerData = {
playerName: playerName
};
const JSONdata = JSON.stringify(playerData);
fetch(`/profile?tags=${JSONdata}`, { method: "GET" }).then((response) => {
if (response.ok) {
document.getElementById('loaderLabel').innerHTML = "Loading Player"
}
else {
alert("Something bad happened.");
};
});
};
loadOldPlayer.addEventListener("click", enterProfile.bind(true));
from flask import Flask, render_template, request
from static.SNEKfiles import SpaceShipGame
import json
game_app = Flask(__name__)
@game_app.route('/')
@game_app.route('/home')
def home():
return render_template("HTMLPage1.html")
@game_app.route('/profile', methods=['GET'])
def profile():
if request.method == 'GET':
playerName = request.args.get('tags')
if playerName != None:
print("got the name")
return render_template("showsPlayer.html")
else:
print("here is issue")
return render_template("playerView.html")
if __name__== "__main__":
game_app.run(debug=True, host='127.0.0.1', port=7777)
Yes my HTML files are badly named, I'll probably get around to fixing that. Eventually.
Solution
I'm inexperienced with this, so I might be completely wrong here. Anyway, try adding the event listener with
loadOldPlayer.addEventListener("click", function() {
enterProfile(true);
});
instead of
loadOldPlayer.addEventListener("click", enterProfile.bind(true));
I think the bind(true) might be causing the empty querystring. If this doesn't work, could you add some debug output?
Also, the return render_template("showsPlayer.html")
successfully returns the html, but the client never actually uses it. Try using
fetch(`/profile?tags=${JSONdata}`, { method: "GET" }).then((response) => {
if (response.ok) {
document.getElementById('loaderLabel').innerHTML = "Loading Player"
return response.text()
}
else {
alert("Something bad happened.");
}
}).then((html) => {
console.log(html) // should show response html
document.open();
document.write(html); // writes response html to body
document.close();
})
Document.write() is considered bad practice, but it is the only way (that I know of, at least) to dynamically replace the entire page.
Answered By - Quackers
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.