Flask – Javascript requests not working? 404 NOT FOUND

Question:

So I’m migrating from apache to using flask, I’ve moved all my css, javascript, csv and Images to static. From there I’ve spent a while changing all the hrefs so everything loads correctly.
Everything the html is loading is working fine, but all of the requests javascript is sending are 404’ing and I’m not sure why.

My directory structure is as follows:
Python:
——-static:
—————css:
—————csv:
————————gamesToday.csv
—————js:
—————Images:
————————logo.png
————————logo-small.png
——-templates:
——————main.html
——-flaskTest.py
My flasktest.py simply loads and renders the main.html file at the moment.

Javascript request for csv file:

$.ajax({
    type: "GET",
    url: "{{url_for('static', filename='csv/gamesToday.csv')}}",
    dataType: "text",
    success: function(data) {processData(data);}
 });

Javascript for loading image:

function logoSizing(){
    if($(window).width() < 992)
        $("#logo").attr("src", "{{url_for('static', filename='Images/small-logo.png");
    else
        $("#logo").attr("src", "{{url_for('static', filename='Images/logo.png");
}

The strange thing is when i move the request for the image into html the image loads correctly, so I know that the file is infact there, so I presume the error is in the fact I can’t make an AJAX call like this? If so, how do I go about making it correctly?

Apologies if this is very simple, just started learning flask today and I’m having serious trouble wrapping my head around it.

Asked By: Danny

||

Answers:

.js files are not parsed by the jinja template engine so it wont replace {{url for...}} with the actual url.

you will need to pass the url in from one of your html templates or hardcode the path

Answered By: Joran Beasley

for js files:

{{url_for(‘static’,filename=’main.js’)}}

for images files:

{{url_for(‘static’,filename=’main.js’)}}

example:(adding script in html file)

<script src="{{url_for('static',filename='main.js')}}"></script>
Answered By: Umit KOC
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.