1

I have some dynamically generated content populated by JS within the following attribute:

<div id="connection" class="fp"> XX </div>

How can I have the generated content "XX" available in my Python code?

I'm using Flask framework. I know that using Input and Select attribute its possible as for example,

<input name= EMAILS type="email">

then,

@app.route("/", methods=['POST'])
def upload():
    request.form.get('EMAILS')

But it's not possible for <p> or <div>.

katiepy
  • 95
  • 1
  • 1
  • 6

1 Answers1

0

You can use ajax. First, in your template (named home.html), create a script with jquery:

<html>
  <body>
   <div id="connection" class="fp"> XX </div>
   <button id="hit" type="button" name="">get text</button>
   <div id='placeholder'></div>
  </body>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
 <script>
  $(document).ready(function() {
   $('#hit').click(function() {
    var text = $('#connection').text();
   $.ajax({
    url: "/get_text",
    type: "get",
    data: {result:text},
    success: function(response) {
    $("#placeholder").html(response);
    },
     error: function(xhr) {
      //Do Something to handle error
   }
    });
 });
 });
</script>
</html>

When the button is clicked, the text from the div element is captured and sent to the backend. However, the backend must return a response as well. To do that, create the route with flask, and access the result returned by ajax, and return some HTML:

@app.route('/')
def home():
  return flask.render_template('home.html')

@app.route('/get_text')
def get_text():
  returned_result = flask.request.args.get('result')
  print(returned_result)
  #do something with returned_result
  return '<strong>Thanks!</strong>'

When I run the script, the result below is printed to the terminal:

XX
Ajax1234
  • 69,937
  • 8
  • 61
  • 102