How to use AJAX in Flask to iterate through a list









up vote
2
down vote

favorite












Problem



I am trying to display image-files using AJAX in Flask. More specifically, I want to display an image once a button is clicked and display the next image once the button is clicked again (like a slide-show). The filenames of the images are stored in my database. I query the database to get a list of filenames for the current user and combine each filename with the rest of the path (path to where the images are stored on disk) in order to display the image.



So far, I manage to get the first image of the current user. However, I can't figure out a way to keep track of which image is the next one to show.



I tried using a global variable as a counter (file_counter) which should serve as an index. I want to increase file_counter by 1 each time an ajax request is made in order to get the next file but the counter does not increase upon subsequent calls nor does it throw an error.



Question



How do I need to initialize the global variable (file_counter) in order for it to store its value across multiple calls? Furthermore, is the usage of global variables the correct way of doing this?



HTML



<div id="ajax-field"></div>
<button class="btn btn-block" id="next-button"><p>Next Image!</p></button>


AJAX:



$('#next-button').click(function()
$("#ajax-field").text("");
$.ajax(
url: "/get_data",
type: "POST",
success: function(resp)
$('#ajax-field').append(resp.data);

);
);


Routing:



global filenames
global file_count
@app.route("/get_data", methods=['POST'])
def get_data():
try: # Is intended to fail on the first run in order for the global variables to be initialized. However it keeps failing on subsequent runs
display_img = filenames[file_count]
file_count +=1
except:

filenames =
# current_user.uploads returns all file-objects of the current user
user_uploads = current_user.uploads
for file in user_uploads:
# file.filename returns the respective filename of the image
filenames.append(file.filename)
#filenames is now a list of filenames i.e. ['a.jpg','b.jpg','c.jpg'...]
display_img = filenames[0]
file_count = 1

path = "image_uploads/4_files/"+display_img

return jsonify('data': render_template('ajax_template.html', mylist = path))


ajax_template.html:



<ul>
% block content %
<li>
<img id="selected-image-ajax" src="url_for('static',filename=mylist)" class="img-thumbnail" style="display:block; margin:auto;"></img>
</li>
% endblock content %
</ul>









share|improve this question





















  • I cannot profess to give you best practice but do not use globals here. If anything, store it in session data
    – roganjosh
    Nov 10 at 21:43














up vote
2
down vote

favorite












Problem



I am trying to display image-files using AJAX in Flask. More specifically, I want to display an image once a button is clicked and display the next image once the button is clicked again (like a slide-show). The filenames of the images are stored in my database. I query the database to get a list of filenames for the current user and combine each filename with the rest of the path (path to where the images are stored on disk) in order to display the image.



So far, I manage to get the first image of the current user. However, I can't figure out a way to keep track of which image is the next one to show.



I tried using a global variable as a counter (file_counter) which should serve as an index. I want to increase file_counter by 1 each time an ajax request is made in order to get the next file but the counter does not increase upon subsequent calls nor does it throw an error.



Question



How do I need to initialize the global variable (file_counter) in order for it to store its value across multiple calls? Furthermore, is the usage of global variables the correct way of doing this?



HTML



<div id="ajax-field"></div>
<button class="btn btn-block" id="next-button"><p>Next Image!</p></button>


AJAX:



$('#next-button').click(function()
$("#ajax-field").text("");
$.ajax(
url: "/get_data",
type: "POST",
success: function(resp)
$('#ajax-field').append(resp.data);

);
);


Routing:



global filenames
global file_count
@app.route("/get_data", methods=['POST'])
def get_data():
try: # Is intended to fail on the first run in order for the global variables to be initialized. However it keeps failing on subsequent runs
display_img = filenames[file_count]
file_count +=1
except:

filenames =
# current_user.uploads returns all file-objects of the current user
user_uploads = current_user.uploads
for file in user_uploads:
# file.filename returns the respective filename of the image
filenames.append(file.filename)
#filenames is now a list of filenames i.e. ['a.jpg','b.jpg','c.jpg'...]
display_img = filenames[0]
file_count = 1

path = "image_uploads/4_files/"+display_img

return jsonify('data': render_template('ajax_template.html', mylist = path))


ajax_template.html:



<ul>
% block content %
<li>
<img id="selected-image-ajax" src="url_for('static',filename=mylist)" class="img-thumbnail" style="display:block; margin:auto;"></img>
</li>
% endblock content %
</ul>









share|improve this question





















  • I cannot profess to give you best practice but do not use globals here. If anything, store it in session data
    – roganjosh
    Nov 10 at 21:43












up vote
2
down vote

favorite









up vote
2
down vote

favorite











Problem



I am trying to display image-files using AJAX in Flask. More specifically, I want to display an image once a button is clicked and display the next image once the button is clicked again (like a slide-show). The filenames of the images are stored in my database. I query the database to get a list of filenames for the current user and combine each filename with the rest of the path (path to where the images are stored on disk) in order to display the image.



So far, I manage to get the first image of the current user. However, I can't figure out a way to keep track of which image is the next one to show.



I tried using a global variable as a counter (file_counter) which should serve as an index. I want to increase file_counter by 1 each time an ajax request is made in order to get the next file but the counter does not increase upon subsequent calls nor does it throw an error.



Question



How do I need to initialize the global variable (file_counter) in order for it to store its value across multiple calls? Furthermore, is the usage of global variables the correct way of doing this?



HTML



<div id="ajax-field"></div>
<button class="btn btn-block" id="next-button"><p>Next Image!</p></button>


AJAX:



$('#next-button').click(function()
$("#ajax-field").text("");
$.ajax(
url: "/get_data",
type: "POST",
success: function(resp)
$('#ajax-field').append(resp.data);

);
);


Routing:



global filenames
global file_count
@app.route("/get_data", methods=['POST'])
def get_data():
try: # Is intended to fail on the first run in order for the global variables to be initialized. However it keeps failing on subsequent runs
display_img = filenames[file_count]
file_count +=1
except:

filenames =
# current_user.uploads returns all file-objects of the current user
user_uploads = current_user.uploads
for file in user_uploads:
# file.filename returns the respective filename of the image
filenames.append(file.filename)
#filenames is now a list of filenames i.e. ['a.jpg','b.jpg','c.jpg'...]
display_img = filenames[0]
file_count = 1

path = "image_uploads/4_files/"+display_img

return jsonify('data': render_template('ajax_template.html', mylist = path))


ajax_template.html:



<ul>
% block content %
<li>
<img id="selected-image-ajax" src="url_for('static',filename=mylist)" class="img-thumbnail" style="display:block; margin:auto;"></img>
</li>
% endblock content %
</ul>









share|improve this question













Problem



I am trying to display image-files using AJAX in Flask. More specifically, I want to display an image once a button is clicked and display the next image once the button is clicked again (like a slide-show). The filenames of the images are stored in my database. I query the database to get a list of filenames for the current user and combine each filename with the rest of the path (path to where the images are stored on disk) in order to display the image.



So far, I manage to get the first image of the current user. However, I can't figure out a way to keep track of which image is the next one to show.



I tried using a global variable as a counter (file_counter) which should serve as an index. I want to increase file_counter by 1 each time an ajax request is made in order to get the next file but the counter does not increase upon subsequent calls nor does it throw an error.



Question



How do I need to initialize the global variable (file_counter) in order for it to store its value across multiple calls? Furthermore, is the usage of global variables the correct way of doing this?



HTML



<div id="ajax-field"></div>
<button class="btn btn-block" id="next-button"><p>Next Image!</p></button>


AJAX:



$('#next-button').click(function()
$("#ajax-field").text("");
$.ajax(
url: "/get_data",
type: "POST",
success: function(resp)
$('#ajax-field').append(resp.data);

);
);


Routing:



global filenames
global file_count
@app.route("/get_data", methods=['POST'])
def get_data():
try: # Is intended to fail on the first run in order for the global variables to be initialized. However it keeps failing on subsequent runs
display_img = filenames[file_count]
file_count +=1
except:

filenames =
# current_user.uploads returns all file-objects of the current user
user_uploads = current_user.uploads
for file in user_uploads:
# file.filename returns the respective filename of the image
filenames.append(file.filename)
#filenames is now a list of filenames i.e. ['a.jpg','b.jpg','c.jpg'...]
display_img = filenames[0]
file_count = 1

path = "image_uploads/4_files/"+display_img

return jsonify('data': render_template('ajax_template.html', mylist = path))


ajax_template.html:



<ul>
% block content %
<li>
<img id="selected-image-ajax" src="url_for('static',filename=mylist)" class="img-thumbnail" style="display:block; margin:auto;"></img>
</li>
% endblock content %
</ul>






python jquery ajax flask






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 21:38









AaronDT

6491424




6491424











  • I cannot profess to give you best practice but do not use globals here. If anything, store it in session data
    – roganjosh
    Nov 10 at 21:43
















  • I cannot profess to give you best practice but do not use globals here. If anything, store it in session data
    – roganjosh
    Nov 10 at 21:43















I cannot profess to give you best practice but do not use globals here. If anything, store it in session data
– roganjosh
Nov 10 at 21:43




I cannot profess to give you best practice but do not use globals here. If anything, store it in session data
– roganjosh
Nov 10 at 21:43












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










As @roganjosh pointed out, a session is the optimal way to store information across multiple requests. This solution presents an implementation of the photo display using flask.session to store the counter:



import flask, random, string
app = flask.Flask(__name__)
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#to use flask.session, a secret key must be passed to the app instance

@app.route('/display_page', methods=['GET'])
def display_page():
'''function to return the HTML page to display the images'''
flask.session['count'] = 0
_files = [i.filename for i in current_user.uploads]
return flask.render_template('photo_display.html', photo = _files[0])

@app.route('/get_photo', methods=['GET'])
def get_photo():
_direction = flask.request.args.get('direction')
flask.session['count'] = flask.session['count'] + (1 if _direction == 'f' else - 1)
_files = [i.filename for i in current_user.uploads]
return flask.jsonify('photo':_files[flask.session['count']], 'forward':str(flask.session['count']+1 < len(_files)), 'back':str(bool(flask.session['count'])))


The display_page function will be called when a user accesses the /display_page route and will set the count to 0. get_photo is bound to the /get_photo route and will be called when the ajax request is sent.



photo_display.html:



<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class='image_display'>
<img src="photo" id='photo_display' height="100" width="100">
<table>
<tr>
<td class='back'></td>
<td class='forward'><button id='go_forward' class='navigate'>Forward</button></td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function()
$('.image_display').on('click', '.navigate', function()
var direction = 'b';
if ($(this).prop('id') === 'go_forward')
direction = 'f';


$.ajax(
url: "/get_photo",
type: "get",
data: direction: direction,
success: function(response)
$('#photo_display').attr('src', response.photo);
if (response.back === "True")
$('.back').html("<button id='go_back' class='navigate'>Back</button>")

else
$('#go_back').remove();

if (response.forward === "True")
$('.forward').html("<button id='go_forward' class='navigate'>Forward</button>")

else
$('#go_forward').remove();


,

);
);
);
</script>
</html>


The javascript in display_page.html communicates with the backend, and updates the img tag src accordingly. The script adds or removes the navigation buttons, depending on the current count value.




Demo:



To test the solution above, I created an image folder to store random photographs to display:



enter image description here






share|improve this answer






















  • amazing! thank you so much!
    – AaronDT
    Nov 12 at 9:16










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243661%2fhow-to-use-ajax-in-flask-to-iterate-through-a-list%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










As @roganjosh pointed out, a session is the optimal way to store information across multiple requests. This solution presents an implementation of the photo display using flask.session to store the counter:



import flask, random, string
app = flask.Flask(__name__)
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#to use flask.session, a secret key must be passed to the app instance

@app.route('/display_page', methods=['GET'])
def display_page():
'''function to return the HTML page to display the images'''
flask.session['count'] = 0
_files = [i.filename for i in current_user.uploads]
return flask.render_template('photo_display.html', photo = _files[0])

@app.route('/get_photo', methods=['GET'])
def get_photo():
_direction = flask.request.args.get('direction')
flask.session['count'] = flask.session['count'] + (1 if _direction == 'f' else - 1)
_files = [i.filename for i in current_user.uploads]
return flask.jsonify('photo':_files[flask.session['count']], 'forward':str(flask.session['count']+1 < len(_files)), 'back':str(bool(flask.session['count'])))


The display_page function will be called when a user accesses the /display_page route and will set the count to 0. get_photo is bound to the /get_photo route and will be called when the ajax request is sent.



photo_display.html:



<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class='image_display'>
<img src="photo" id='photo_display' height="100" width="100">
<table>
<tr>
<td class='back'></td>
<td class='forward'><button id='go_forward' class='navigate'>Forward</button></td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function()
$('.image_display').on('click', '.navigate', function()
var direction = 'b';
if ($(this).prop('id') === 'go_forward')
direction = 'f';


$.ajax(
url: "/get_photo",
type: "get",
data: direction: direction,
success: function(response)
$('#photo_display').attr('src', response.photo);
if (response.back === "True")
$('.back').html("<button id='go_back' class='navigate'>Back</button>")

else
$('#go_back').remove();

if (response.forward === "True")
$('.forward').html("<button id='go_forward' class='navigate'>Forward</button>")

else
$('#go_forward').remove();


,

);
);
);
</script>
</html>


The javascript in display_page.html communicates with the backend, and updates the img tag src accordingly. The script adds or removes the navigation buttons, depending on the current count value.




Demo:



To test the solution above, I created an image folder to store random photographs to display:



enter image description here






share|improve this answer






















  • amazing! thank you so much!
    – AaronDT
    Nov 12 at 9:16














up vote
1
down vote



accepted










As @roganjosh pointed out, a session is the optimal way to store information across multiple requests. This solution presents an implementation of the photo display using flask.session to store the counter:



import flask, random, string
app = flask.Flask(__name__)
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#to use flask.session, a secret key must be passed to the app instance

@app.route('/display_page', methods=['GET'])
def display_page():
'''function to return the HTML page to display the images'''
flask.session['count'] = 0
_files = [i.filename for i in current_user.uploads]
return flask.render_template('photo_display.html', photo = _files[0])

@app.route('/get_photo', methods=['GET'])
def get_photo():
_direction = flask.request.args.get('direction')
flask.session['count'] = flask.session['count'] + (1 if _direction == 'f' else - 1)
_files = [i.filename for i in current_user.uploads]
return flask.jsonify('photo':_files[flask.session['count']], 'forward':str(flask.session['count']+1 < len(_files)), 'back':str(bool(flask.session['count'])))


The display_page function will be called when a user accesses the /display_page route and will set the count to 0. get_photo is bound to the /get_photo route and will be called when the ajax request is sent.



photo_display.html:



<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class='image_display'>
<img src="photo" id='photo_display' height="100" width="100">
<table>
<tr>
<td class='back'></td>
<td class='forward'><button id='go_forward' class='navigate'>Forward</button></td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function()
$('.image_display').on('click', '.navigate', function()
var direction = 'b';
if ($(this).prop('id') === 'go_forward')
direction = 'f';


$.ajax(
url: "/get_photo",
type: "get",
data: direction: direction,
success: function(response)
$('#photo_display').attr('src', response.photo);
if (response.back === "True")
$('.back').html("<button id='go_back' class='navigate'>Back</button>")

else
$('#go_back').remove();

if (response.forward === "True")
$('.forward').html("<button id='go_forward' class='navigate'>Forward</button>")

else
$('#go_forward').remove();


,

);
);
);
</script>
</html>


The javascript in display_page.html communicates with the backend, and updates the img tag src accordingly. The script adds or removes the navigation buttons, depending on the current count value.




Demo:



To test the solution above, I created an image folder to store random photographs to display:



enter image description here






share|improve this answer






















  • amazing! thank you so much!
    – AaronDT
    Nov 12 at 9:16












up vote
1
down vote



accepted







up vote
1
down vote



accepted






As @roganjosh pointed out, a session is the optimal way to store information across multiple requests. This solution presents an implementation of the photo display using flask.session to store the counter:



import flask, random, string
app = flask.Flask(__name__)
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#to use flask.session, a secret key must be passed to the app instance

@app.route('/display_page', methods=['GET'])
def display_page():
'''function to return the HTML page to display the images'''
flask.session['count'] = 0
_files = [i.filename for i in current_user.uploads]
return flask.render_template('photo_display.html', photo = _files[0])

@app.route('/get_photo', methods=['GET'])
def get_photo():
_direction = flask.request.args.get('direction')
flask.session['count'] = flask.session['count'] + (1 if _direction == 'f' else - 1)
_files = [i.filename for i in current_user.uploads]
return flask.jsonify('photo':_files[flask.session['count']], 'forward':str(flask.session['count']+1 < len(_files)), 'back':str(bool(flask.session['count'])))


The display_page function will be called when a user accesses the /display_page route and will set the count to 0. get_photo is bound to the /get_photo route and will be called when the ajax request is sent.



photo_display.html:



<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class='image_display'>
<img src="photo" id='photo_display' height="100" width="100">
<table>
<tr>
<td class='back'></td>
<td class='forward'><button id='go_forward' class='navigate'>Forward</button></td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function()
$('.image_display').on('click', '.navigate', function()
var direction = 'b';
if ($(this).prop('id') === 'go_forward')
direction = 'f';


$.ajax(
url: "/get_photo",
type: "get",
data: direction: direction,
success: function(response)
$('#photo_display').attr('src', response.photo);
if (response.back === "True")
$('.back').html("<button id='go_back' class='navigate'>Back</button>")

else
$('#go_back').remove();

if (response.forward === "True")
$('.forward').html("<button id='go_forward' class='navigate'>Forward</button>")

else
$('#go_forward').remove();


,

);
);
);
</script>
</html>


The javascript in display_page.html communicates with the backend, and updates the img tag src accordingly. The script adds or removes the navigation buttons, depending on the current count value.




Demo:



To test the solution above, I created an image folder to store random photographs to display:



enter image description here






share|improve this answer














As @roganjosh pointed out, a session is the optimal way to store information across multiple requests. This solution presents an implementation of the photo display using flask.session to store the counter:



import flask, random, string
app = flask.Flask(__name__)
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#to use flask.session, a secret key must be passed to the app instance

@app.route('/display_page', methods=['GET'])
def display_page():
'''function to return the HTML page to display the images'''
flask.session['count'] = 0
_files = [i.filename for i in current_user.uploads]
return flask.render_template('photo_display.html', photo = _files[0])

@app.route('/get_photo', methods=['GET'])
def get_photo():
_direction = flask.request.args.get('direction')
flask.session['count'] = flask.session['count'] + (1 if _direction == 'f' else - 1)
_files = [i.filename for i in current_user.uploads]
return flask.jsonify('photo':_files[flask.session['count']], 'forward':str(flask.session['count']+1 < len(_files)), 'back':str(bool(flask.session['count'])))


The display_page function will be called when a user accesses the /display_page route and will set the count to 0. get_photo is bound to the /get_photo route and will be called when the ajax request is sent.



photo_display.html:



<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class='image_display'>
<img src="photo" id='photo_display' height="100" width="100">
<table>
<tr>
<td class='back'></td>
<td class='forward'><button id='go_forward' class='navigate'>Forward</button></td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function()
$('.image_display').on('click', '.navigate', function()
var direction = 'b';
if ($(this).prop('id') === 'go_forward')
direction = 'f';


$.ajax(
url: "/get_photo",
type: "get",
data: direction: direction,
success: function(response)
$('#photo_display').attr('src', response.photo);
if (response.back === "True")
$('.back').html("<button id='go_back' class='navigate'>Back</button>")

else
$('#go_back').remove();

if (response.forward === "True")
$('.forward').html("<button id='go_forward' class='navigate'>Forward</button>")

else
$('#go_forward').remove();


,

);
);
);
</script>
</html>


The javascript in display_page.html communicates with the backend, and updates the img tag src accordingly. The script adds or removes the navigation buttons, depending on the current count value.




Demo:



To test the solution above, I created an image folder to store random photographs to display:



enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 11 at 3:21

























answered Nov 10 at 23:20









Ajax1234

38.6k42351




38.6k42351











  • amazing! thank you so much!
    – AaronDT
    Nov 12 at 9:16
















  • amazing! thank you so much!
    – AaronDT
    Nov 12 at 9:16















amazing! thank you so much!
– AaronDT
Nov 12 at 9:16




amazing! thank you so much!
– AaronDT
Nov 12 at 9:16

















 

draft saved


draft discarded















































 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243661%2fhow-to-use-ajax-in-flask-to-iterate-through-a-list%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Barbados

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3