I want to change the attribute value in the index.html file from the external JavaScript file linked to that HTML file.
I have folder structure as: folder structure
I can easily give path from html file using: {{url_for('static', filename='image_path')}}
But, this does not work while using in external JavaScript file.
success: function (data) {
var image_name = data["img_name"]
var image_path = data["image_path"]
// I have image_path and image_name ready but could not find the exact method to use this...
// I want to use the image saved in "uploads" folder
document.getElementById("uploadimg").setAttribute("src", {{url_for('uploads', filename='image_name')}});
}
So, How can I use the absolute path or image_name to change the image in the frontend? Thanks!
A common technique used by server-rendered pages is to create a JSON script thing in their HTML and query it from the (external) JS.
For example, in your Flask server, you'd so something like:
import json
# ...
@app.route("/page")
def page():
data = json.dumps({
"uploadImageUrl": url_for("uploads", filename="image_name")
# you can include other data
})
return render_template("page.html", data=data)
Then stick this into your <head> tag:
<script type="application/json" id="data">{{ data }}</script>
Note that the browser only executes JavaScript when it is in a script with type text/javascript (default value if not specified), so when we add application/json, the browser will just leave our weird-smelling script tag alone.
In your external JavaScript you could do something like:
const data = JSON.parse(document.getElementById("data"));
// somewhere else in your code:
document.getElementById("uploadimg").setAttribute("src", data.uploadImageUrl);