I am using FLASK + Ajax to make login page. It should redirects to another page in case of correct username and password.
I made a form. and the request is passing successfully. and I can catch the data in python ( flask ). but my issue that no redirect happens after rendering the page. with render_template
Here is to redirect to login page when requesting the root url
@app.route('/')
def OperationPage():
log_screenprint('User Has Requested / URL >> Redirect to /login')
return redirect(url_for('page_login'))
And this is the function which verify the username and password. then it should redirect to the next page
@app.route('/login' , methods=["POST","GET"])
def page_login() :
log_screenprint('Got Request From GUI User to login With Cred.')
for key,value in securityFile.items() :
dbUser = securityFile[key]['username']
dbpass = securityFile[key]['defaultpass']
username = request.form.get('username')
password = request.form.get('password')
sessionId = request.form.get('session')
if dbUser == username :
if dbpass == password :
socketio.emit('userDb' , json.dumps(securityFile[key]) , session = sessionId)
return render_template('/index.html' , title= 'Home Page')
return render_template('/login.html')
and this is the request I am using in javascript.
$('#login-form').submit(function (e) {
e.preventDefault();
var username = document.querySelector('.login-username').value
var password = document.querySelector('.login-password').value
$.ajax({
url: '/login',
data: {
username: username,
password: password,
session : (socket.id),
},
type: 'POST',
success: function (response) {
console.log('response');
},
error: function (error) {
console.log(error);
}
});
});
The issue again that. even the correct username and password. the index.html is not rendering
While using ajax you're in charge of what to do with server response. The response returned by server is html webpage (index.html) which you need to show for user. In your case you're just printing word 'response' to the webpage console:
success: function (response) {
console.log('response');
},
I suggest doing it other way. I would create another route:
@app.route('/index')
def index():
return render_template('/index.html' , title= 'Home Page')
and redirected user to it when server response would be successful.
success: function (response) {
window.location.replace('index')
},
It also needs some changes for auhtentication function, since your server returns succesful http code every time. You can use something like:
return "", 200
for successful login, and
return "", 401
for failed.