Return Json object to HTML

I’m developing a web app where I need to update the configuration of a certain type of graph. To do so, I’m using Python3 with flask and html.

I want to update the configuration dynamically, which means that I don’t want to use the function render_template and instead, I want to use return jsonify(message) .

Below I included the function that I want to use to update the data. This function is used as a callback on the rest of my system and those prints are being executed well, which means that on the flask side, everything seems to be okay. However, I don’t know what I should put on the html side to receive this data. Here is the code that I’m using in flask to send the data:

@app.route('/online_visualization_update') def online_visualization_update(msg):     print("I should change the network.")     print("The message was ", msg)     with app.app_context():         return jsonify(msg.transition, msg.marking) 

This is the code I tried to implement on html to receive the data sent by flask:

<script type=text/javascript>  fetch('/online_visualization_update')          .then(response => response.json())          .then(data => console.log(data))          .catch((error) => {console.error('Error:', error); });  </script> 

Currently, this is not working because the the fetch is being performed every time I open the webapp. What am I doing wrong?

Ideally, I would like to have a function on javascript that is executed only when it receives the data from flask but I don’t know whether fetch works like that or not.

Thank you

Add Comment
1 Answer(s)

For that you need to use Fetch API in javascript like this

  // write function like this   function callApi(){     fetch('/online_visualization_update')      .then(response => response.json())       .then(data => console.log(data))     .catch((error) => {       console.error('Error:', error);     });    } 

Refer this for more about fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Add this code in your Html page:

   <Div class="container">             <button type="button" onclick="callApi()">Call func</button>             <!--you need to call function like this whenever you need data -->     </Div> 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.