0

I want to call a function in python and print a variable in a div tag in a separate html file, then transfer the content into the div in my index.html

index.html:

<div id="logger">
</div>

<form action="/write_log" method="post">
    <button name="button" type="submit">Show Log</button>
</form>

<script>
var logger_js=localStorage.getItem("log");
document.getElementById("logger").innerHTML=logger_js
</script>

logger.html (to prevent Flask from rendering twice the index.html):

<div id="update_logger">
<script>
localStorage.setItem("log", {{ logger }});
</script>
</div>

flask.py

@app.route('/write_log',methods=['POST'])

def log():

    logger = upload.logger
    return jsonify('', render_template('logger.html', logger=logger))

Now the problem is that once I click the button, the browser directs to /write_log instead of staying on index.html. I want that the printing is inside of the div tag on index.html

UPDATE:

index.html:

<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>
<div id="logger">

</div>

    <button name="button" type="submit">Show Log</button>


<script>
    $("#button").click(function () { // assuming submit button as id btn
  $.ajax({
    type: "POST", //
    url: "/write_log", // url to the function
    data: {
      // include data here if you want to send something in json format
    },
    success: function (response) {
      $("#update_logger").html(response) // manipulate the dom
      localStorage.setItem("log", response);
        console.log(response);
    },
  });
});

</script>

</body>
</html>

flask.py:

@app.route('/write_log',methods=['POST'])

def log():

    if request.method == "POST":
       logger = upload.logger
       return logger
stanvooz
  • 522
  • 3
  • 19

1 Answers1

1

You can use ajax in jquery to easily send and recieve data without page reload and then manipulate the dom using javascript.

rather than creating a seperate file make a div in index where you want to show the result.

include jquery before this

<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>

javascript:

$("#btn").click(function () { // assuming submit button as id btn
  $.ajax({
    type: "POST", //
    url: "/write_log", // url to the function
    data: {
      // include data here if you want to send something in json format
    },
    success: function (response) {
      $("#update_logger").html(response) // manipulate the dom
      localStorage.setItem("log", response);
    },
  });
});

Python

if request.method == "POST":
   logger = upload.logger
   return logger
charchit
  • 1,492
  • 2
  • 6
  • 17