2

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?

Deik
  • 134
  • 9
  • Nothing is leaping out at me. Use the debugging tools in your browser. Make sure there are no errors reported. Make sure the Network tab shows the request for the script and that it gets a response. Use a [validator](https://validator.nu/) on your HTML. – Quentin Feb 05 '21 at 21:54
  • Make sure Flask is expanding the `{{url_for...}}` to the correct URL of the JS file. – Barmar Feb 05 '21 at 22:02
  • So do you see the request in the network panel? Do you inspect the sources and file the file? – epascarello Feb 05 '21 at 22:03
  • I can confirm the source is correct, I actually tried a static url too so I don't think that's the problem. – Deik Feb 05 '21 at 22:06
  • It has nothing to do with the error, but you don't need `type=text/javascript` on there. It's unquoted, which I guess could cause problems? Try quoting or removing it. – Heretic Monkey Feb 05 '21 at 22:08
  • I've removed it so now it's just: `` but the output is the same. – Deik Feb 05 '21 at 22:10
  • If you put `console.log("form.js loading");` in `form.js`, do you see the message? – Barmar Feb 05 '21 at 22:11
  • I put `console.log("form.js loading");` right before after `var myForm = $('#myForm');` and in a couple other places and it never shows on the console! Also upon further inspection, I actually checked out the form.js file in source and it's completely empty? – Deik Feb 05 '21 at 22:26
  • Might be a caching issue. Try emptying your browser cache. Also make sure you've deployed your JS file to the server you're hitting with your browser. – Heretic Monkey Feb 05 '21 at 22:34
  • I've cancelled and re-ran my .py app, closed my browser and tried my page again and it's the same thing. I guess I'll just keep it in-line for now, thx for everyone's help so far! – Deik Feb 05 '21 at 23:00

1 Answers1

1

I'm the author of the Flask Ajax Example project that you're working with. I've added a new branch that moves the JS into a separate file that's now inside of a static directory: https://github.com/YellowSharkMT/flask-ajax-example/tree/example-with-static-js-file

I can't say for certain what the issue may have been - the url_for function that you were using in your template above should have done the trick. In my update, I simply added this line to the home.html template:

<script src="{{ url_for('static', filename='js/form.js') }}"></script>

And that's obviously nearly the same thing that you had above. One thing I'll add about Flask is that my example did NOT have debug mode enabled, and I've now enabled that in a separate commit. It makes development a bit easier by adding features like auto-reloading (of the python server) and less-aggressive caching. Go ahead and check that branch out, and let me know if you have any issues - good luck!

YellowShark
  • 2,169
  • 17
  • 17
  • 1
    Haha I'm really glad I thought of just pming you on reddit. Anyways, I tried what you did and separated the jquery src and the form.js into a block script and it worked. I'm really unsure why this is the case so if you have any clues please feel free to let us know! – Deik Feb 08 '21 at 15:23
  • Glad you did! My best guess is that caching was probably the issue - you could test this by deleting the line with `DEBUG = True` in the .py script, and then make some changes to the JS script and refresh the browser to see if they get picked up. My theory is that even after restarting the app, your browser will still cache the JS script. (Might be related to a different Flask question that I've answered: https://stackoverflow.com/questions/41144565/flask-does-not-see-change-in-js-file/41150548#41150548). – YellowShark Feb 08 '21 at 16:37