TAGS :Viewed: 4 - Published at: a few seconds ago

[ jquery .load with python flask ]

I am trying to use jquery .load in my flask app to add a div every time the user presses a button to add a new div, but it can't find the html file.

The function in question.

$(document).ready(function(){
        $("#add").click(function(){
            $("#form").load('/templates/info.html');
        })
});

The info.html file only hold a short div section of html.

index.html the code, where I want to load the info.html div after the form.

  <form id="form" action="{{ url_for('get_data') }}" method="post">
        <input type="button" name="add" value="Add" id="add">
        <input type="submit" id="submit" value="To XML">
    </form>

/templates/info.html

 <div id="info">
     <label>name</label>
     <input type="text" name="name">
     <br>
     <label>asfd</label>
     <input type="text" name="asfd">
      <br>
 </div>

I keep getting this 404 error.

127.0.0.1 - - [04/Mar/2014 19:55:50] "GET /templates/info.html HTTP/1.1" 404 -

I am running the flask app locally, and /template/info.html is the correct path. I just don't know why it doesn't load in that html. I am able to make it work when I use the jquery function and .append() and put the long html string into the append function, but add the info.html gets longer I just want to be able to load the whole file.

Any help would be great thanks.

Answer 1


Your view definition within the flask app should return the info.html. In other words, you should have a route and a method in your flask application as:

@app.route('/info')
def info(name):
    return render_template('info.html')

Now in your jquery code you can load the url /info. Flask by default looks for templates in the templates folder, so no need to explicitly mention that in the URL