I've been trying to learn how to implement AJAX and so far I've been tinkering with this jQuery example.
The code is located at static/js/form.js
(function ($, window, document) {
/* globals window, jQuery, document, console */
// enable this return statement to disable Ajax submission
// return;
$(document).ready(function () {
var myForm = $('#myForm');
myForm.on('submit', function (e) {
e.preventDefault();
var data = myForm.serialize();
$.post('/my-ajax-endpoint', data, function (result) {
if (result.success) {
alert(result.message);
} else {
alert('Error: ' + result.message);
}
console.log(result);
});
})
});
}(jQuery, window, document))
My html works when I have the above inline like this:
<html lang="en">
<head>
<title>Flask-WTF + Ajax Example </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
{% block content %}{% endblock %}
<script type="text/javascript">
(function ($, window, document) {
/* globals window, jQuery, document, console */
// enable this return statement to disable Ajax submission
// return;
$(document).ready(function () {
var myForm = $('#myForm');
myForm.on('submit', function (e) {
e.preventDefault();
var data = myForm.serialize();
$.post('/my-ajax-endpoint', data, function (result) {
if (result.success) {
alert(result.message);
} else {
alert('Error: ' + result.message);
}
console.log(result);
});
})
});
}(jQuery, window, document))
</script>
</body>
</html>
But when I try to reference it as an external file like this:
<head>
<title>Flask-WTF + Ajax Example </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type=text/javascript src="{{url_for('static', filename='js/form.js') }}"></script>
</head>
It doesn't seem to do anything.
I've also tried to put it just before </body>
tag and still no go.
I don't have any working knowledge of JavaScript or jQuery, so if it's something simple then I apologize in advance. I am learning Flask and I wanted to try submitting form data without refreshing and it led me to down this rabbit hole.
EDIT: form.js shows up in console under sources but it's completely blank?