I am writing a small web app with Flask that accepts user input in a form to log them in. I want to use AJAX to query the server so I can validate the user input and display an error message without having to reload the page. So far I have not had success doing so, as each time the page reloads to display the message when the data is submitted.
I have a form here:
<form action="/test" method="post">
<input type="text" id="username" name="username" placeholder="Username" autocomplete="off" autofocus>
<input type="password" id="password" name="password" placeholder="Password" autocomplete="off">
<button id="login">Submit</button>
<div id="error-message"></div>
</form>
with the following jQuery script:
$(function() {
$('#login').bind('click', function() {
var data = {
username: document.getElementById("username").val(),
password: document.getElementById("password").val()
}, validateInput(data);
});
function validateInput(data) {
$.ajax({
url: "/test",
type: "POST",
dataType: "json",
success: function(data) {
$("#error-message").replaceWith(data.error);
}
});
}
});
Finally, my Flask function returns return jsonify({'error': 'Error message'})
The result of this is that upon clicking the submit button, the page reloads and presents me with a blank screen with just the message {"error":"Error message"} or {"error":"Success message"}, depending on whether the input was successful or not. So it is validating the data correctly, it just ends up loading the message on a new page, rather than in the <div> as it should.
I made sure jQuery is set up properly in the <head>, and when I tried submitting something like this before with non-form data, just a variable set up in the app.py file itself, it worked exactly as intended (i.e., page did not reload upon submission). So, this says to me that my issue has something to do with getting data from forms specifically. I am almost certain preventDefault() is not relevant here as I do not use type=submit in the first place.
EDIT: The suggestion that the question here answers the question does not quite work; appending type="button" to the <button> tag simply stops the form from being submitted, which does not help my problem. The form just sits inert and doesn't do anything.
Is there anything you can see here that I am missing? I am still quite new to JavaScript in general, and especially jQuery/AJAX, so it may be something obvious. Any help is greatly appreciated!