0

How i can pass a string from JQuery function to Flask code? I'm trying to use in Flask code something like this: imname = request.args.get('filename')but it doesn't work.

What i have to write in my flask code to return 'filename' of JQuery function?

JQuery function:

<script type = "text/javascript">
$(document).ready(function(){
  $('img').click(function() {
    var src = $(this).attr('src'),
        filename = src.substring(src.lastIndexOf('/')+ 1);
    $('img').removeClass('selected');
    $(this).addClass('selected');
    $('.selected-image span').text(filename);
  });
});
</script>
Teo
  • 41
  • 1
  • 1
  • 6
  • You should use [AJAX](http://api.jquery.com/jquery.ajax/) and receive on Flask side whatever parameters you send with it and process them accordingly :) – errata May 31 '17 at 09:00
  • Unfortunely i don't know AJAX...can you write me what i have to do or it is too long? – Teo May 31 '17 at 10:31
  • you want to access `filename` value in flask backend? – Pradeepb May 31 '17 at 10:37
  • @Teo Ah, sorry for confusion, AJAX is just a jQuery method, meaning it is a JavaScript... :) I added an answer with a bit more explanation. – errata May 31 '17 at 10:44

1 Answers1

1

You should use AJAX calls on your JavaScript side to call an URL which you set up in your Flask app:

// example code:
$.ajax({
  url: "http://localhost/some_url",
})
.done(function( data ) {
  if ( console && console.log ) {
    console.log( "Sample of data:", data.slice( 0, 100 ) );
  }
});

and then handle it on Flask side something like:

# example code:
@app.route('/some_url')
def some_url_route():
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)
    return jsonify(result=a + b)

returning the data you need back on JavaScript side...

Read more about it here!

errata
  • 5,695
  • 10
  • 54
  • 99
  • Ok thanks! But in flask you call variable 'a' and 'b'...in JQuery where are these variables? And where i have to put the console.log in my code? – Teo May 31 '17 at 11:37
  • As stated, that is just "example code". You will send your variables with the help from AJAX in a different way, depending on method you are using (GET or POST) and name them as you wish. On Flask side, you will use the same names to process them further. Check out [this answer](https://stackoverflow.com/a/18697134/175793) to get better idea about it. – errata May 31 '17 at 11:40