I am new to programming and wanted to make a webpage for learning purposes.
What I want to do is to display an error that says "Incorrect username/password" upon incorrect login details.
Actually I managed to do it already, however I recently learned more on making "Single Page Applications" using javascript and am trying it out. Apparently it has the advantage of not needing to load so many times.
EDIT: Upon further consideration, I realised that what I have is also sort of a "Single Page Application", my question is actually more of is it possible for Javascript to receive response from Flask without having to render a new HTML?
I want to do something that will allow me to "post" form data to flask (using javascript), and then receive either True or False depending whether login is successful or not. If its unsuccessful, i want to use .innerHTML in javascript to give an error message, otherwise I will redirect to the correct page. The purpose of this is to create a Single Page Application. prevent rendering again a new html template
Right now I managed to do it completely without javascript as below, but just want to know if there is a way to do it as I described above? Thank you for your help!
partial flasktest.py # /check_login does the authentication. /login will render the frontpage and pass the "invalid" parameter.
@app.route('/login')
def login_page():
return render_template('frontpage_login.html', invalid = bool(request.args.get('invalid')))
@app.route('/check_login', methods = ['POST'])
def check_login():
if request.method == 'POST':
password = request.form['Password']
username = request.form['Username']
tempuser = User.query.filter_by(username = username).first()
if tempuser is not None:
if hashpass(password) == tempuser.password:
login_user(tempuser)
flash("Logged in successfully.")
return redirect(url_for('home_page'))
return redirect(url_for('login_page', invalid = True))
frontpage_login.html # basically a normal login page, will render the message if invalid == true.
{% extends 'frontpage_template.html' %}
{% block head %}
<a href="{{ url_for('front_page')}}">Home</a>
<div class = "currentlink"><a href="{{ url_for('login_page') }}">Login</a></div>
<a href="{{ url_for('register_page') }}">Register</a>
{% endblock %}
{% block content %}
<div class = "loginform">
<form action = "{{ url_for('check_login') }}" method = "POST">
<label for="Username" autofocus>Username</label><br>
<input type="text" id = "Username" name = "Username"><br>
<label for="Password">Password</label><br>
<input type="password" id = "Password" name = "Password"><br>
<input id = "Login" type = "submit" value = "Login">
</form>
</div>
{% if invalid == True %}
<p class = 'error'>The username or password is invalid!</p>
{% endif %}
{% endblock %}