0

How to link a javascript file in flask app ?

I try to exactly what I found in exactly similar posts, but their solution not works for me.

Default ways are not working:

<script src="/static/finances.js"></script>

or

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

or

<script src="./static/finances.js"></script>

This following code is in my layout.html page, and it works correctly in my Flask Application:

  <script type="text/javascript">
    $(document).ready(function() {

        $("#category").change(function() {
          $.ajax({
              type: "POST",
              url: "{{ url_for('load_subcategories') }}",
              data: {cat: $(this).val()},
              success: function(data) {
                  $("#subcategory").html(data);
              }
          });
        });

        $("input[name=type]").change(function() {
          $.ajax({
              type: "POST",
              url: "{{ url_for('load_categories') }}",
              data: {type: $('input[name="type"]:checked').val()},
              success: function(data) {
                  $("#category").html(data);
              }
          });
        });

    });
  </script>

But, when I decide to put in a javascript file inside <header> and after jquery.js, it does not work! (the problem)

I already checked a similar problem in another stackoverflow link, but no success yet.

My Flask app is structured like this in directory-site/

run.py

app/
templates/
    layout.html
    ...
static/
    finances.js
Community
  • 1
  • 1
Silas Santiago
  • 545
  • 4
  • 9
  • What does "not working" mean? Are you getting a 404? Are you getting a JavaScript error? – dirn Oct 17 '16 at 21:46
  • No, there are no 404 or javascript errors. This js code works properly in – Silas Santiago Oct 17 '16 at 22:27
  • 1
    You still haven't told us what you mean by "not working." My guess is the problem is related to trying to use Jinja templating in a JavaScript file which isn't possible unless you serve the file yourself (i.e., not through the `static` endpoint). – dirn Oct 17 '16 at 22:30
  • You have `"{{ url_for('load_categories') }}"` **within** the javascript. That will not be expanded when you have `{{ url_for('static', filename='finances.js') }}` – OneCricketeer Oct 17 '16 at 22:30
  • I put a code solution on the answer link, which is http://stackoverflow.com/questions/27917471/pass-parameter-with-python-flask-in-external-javascript – Silas Santiago Oct 17 '16 at 23:50

0 Answers0