0

I know that you can have javascript to call a python flask function and be able to return data to a designated id. Like this:

HTML

<div id = "update"> </div>

<script type="text/javascript">
   var counter = 0;
   window.setInterval(function(){
      $("#update").load("/game?counter=" + counter);
      counter++;
   }, 5000)

views.py

from flask import request

@app.route("/game")
def live_game():
    textlist = ['a','b','c','d']
    counter = request.args.get('counter')
    return "<p> " + textlist[counter] + " </p>"

I found this in a previous post. What I would like to do is update utilize this method in updating some cool justgage that I found online to show the most up to date temperature and humidity readings from my database. Here is the script that I was wanting to use:

HTML

<div class="container">
  <div class="jumbotron">
    <h1>Historical Environmental Readings</h1>      
    <div class="container-fluid" id="dht-container">
      <div id="g1" style="width: 200px; height: 150px;"></div>
      <div id="g2" style="width: 200px; height: 150px;"></div>
    </div>
  </div>
</div>

.....

<script>
        function ajaxd(NodeID) { 
        //reload result into element with id "dht-container"
        $(??????).load("/tempnodeDHT", function() {  alert( "Temp Load was performed." ); });

        
        document.addEventListener("DOMContentLoaded", function (event) {
            var g1 = new JustGage({
                id: "g1",
                value: 50,
                min: -20,
                max: 150,
                title: "DHT Temp",
                label: "temperature",
                pointer: true,
                textRenderer: function (val) {
                    if (val < NODE_EnvCP.low_temp) {
                        return 'Cold';
                    } else if (val > NODE_EnvCP.hot) {
                        return 'Hot';
                    } else if (val === NODE_EnvCP.optimum_temp) {
                        return 'OK';
                    }
                },
            });
            var g2 = new JustGage({
                id: "g2",
                value: 50,
                min: 0,
                max: 100,
                title: "Target",
                label: "Humidity",
                pointer: true,
                textRenderer: function (val) {
                    if (val < NODE_EnvCP.low_hum) {
                        return 'LOW';
                    } else if (val > NODE_EnvCP.high_hum) {
                        return 'HIGH';
                    } else if (val === NODE_EnvCP.optimum_hum) {
                        return 'OK';
                    }
                },
            });

            setInterval(function () {
             (currentTemp, currentHumidity)=ajaxd();
            g1.refresh(currentTemp);
            g2.refresh(currentHumidity);
                return false;
            }, 2500);
        });
    </script>

This is my python flask function: run.py

@app.route('/nodeDHT')
def getLatestDHT():
    NodeID = request.args.get('NodeID')
    df = DAO.Pull_CURRENT_DHT_Node_Data(self, NodeID)
    currentTemp = df.Temperature[0]
    currentHumidity = df.Humidity[0]
    return (currentTemp, currentHumidity)

I was hoping that I could change the ?????? inside

$(??????).load("/nodeDHT", function() {  alert( "Temp Load was performed." ); });

so that the two variables (currentTemp, currentHumidity) would end up back into the javascript portion so that the gages would update every 2.5 seconds. Also, am I passing the variable back to the python flask? there is a variable already pushed to the html when it was rendered.

EDIT:

could I do something like this:

@app.route('/nodeDHT')
def getLatestDHT():
    NodeID = request.args.get('NodeID')
    df = DAO.Pull_CURRENT_DHT_Node_Data(self, NodeID)
    currentTemp = df.Temperature[0]
    currentHumidity = df.Humidity[0]
    return json.dumps(currentTemp, currentHumidity)

and in the javascript side do something like this?

    function ajaxd(NodeID) { 
    //reload result into javascript
    $.get("/nodeDHT",function( currentTemp, currentHumidity ){ console.log($.parseJSON(currentTemp, currentHumidity)});

What I'm really asking is. How can I pass single/multiple variables to the python flask function from the javascript function and then get back a dataframe where I can use column values to update a chart or multiple variables back to the javascript function to be used in a setinterval to be used for multiple functions such as updating justgage

    setInterval(function () {
     (currentTemp, currentHumidity)=ajaxd();
    g1.refresh(currentTemp);
    g2.refresh(currentHumidity);
        return false;
    }, 2500);

---------------------DOUBLE EDIT -----------------------

COULD I DO SOMETHING LIKE THIS:

function UPDATEGAGES(NodeID) { 
$.get('/nodeDHT?NodeID='+NodeID+'&startdatetime='+startdatetime, 
    function(data){ const parsed = JSON.parse(data)};
        g1.refresh(currentTemp);
        g2.refresh(currentHumidity);
});

setInterval(function () {
        UPDATEGAGES(NodeID);
        return false;
    }, 2500);
7
  • So you want to use $.post() and not load HTML content Commented Jul 26, 2021 at 14:52
  • I don't know. would that bring the variables from 'getLatestDHT' back into the script area? Commented Jul 26, 2021 at 14:53
  • Wouldn't passing a JSON array/object be ideal here? jQuery even has a $.getJSON function to skip the JSON stringify/parse steps, although you still need to JSON (de)serialize server-side. In your example, you could probably just use a query parameter (e.g. /nodeDHT?nodeId=123), although you'd still have to serialize the response data. Commented Jul 30, 2021 at 16:39
  • I'm a noob to the javascript side of things...why would you not want to use ajax $.get ? I thought that is the ideal method in returning dataframes from pandas to update charts and real time data Commented Jul 30, 2021 at 17:15
  • @Daniel Do you need to response with two variable in server side? Commented Jul 31, 2021 at 6:37

1 Answer 1

1
+50

If you want to send variables to server in get method, use variables in url

'/tempnodeDHT?NodeID='+your_nod_id+'&anotherVar='+value+'&anotherVar2='+value2

You can access them in your flask server as below

NodeID = request.args['NodeID']
anotherVar = request.args['anotherVar']
anotherVar2 = request.args['anotherVar2']

If you want to send multiple variables from flask server to your front end, send it as JSON

return jsonify({'currentTemp': currentTemp, 'currentHumidity': currentHumidity })

When you handle it the response from the server, again parses it to JSON.

$.get( '/nodeDHT/tempnodeDHT?NodeID='+your_nod_id+'&anotherVar='+value+'&anotherVar2='+value2, function( data ) {
  const parsed = JSON.parse(data)
  // here you can access your 'currentTemp' variable from parsed.currentTemp 
});

EDIT

For your final desired output

function UPDATEGAGES(NodeID, startdatetime) { 
    $.get('/nodeDHT?NodeID='+NodeID+'&startdatetime='+startdatetime, 
        function(data){
            const parsed = JSON.parse(data)
            g1.refresh(parsed.currentTemp);
            g2.refresh(parsed.currentHumidity);
        };
    )
};

setInterval(function () {
        UPDATEGAGES(NodeID, startdatetime);
        return false;
}, 2500);
Sign up to request clarification or add additional context in comments.

11 Comments

ok...so I mistakenly put in tempnodeDHT instead of just /nodeDHT you are saying to use $.get('/nodeDHT?NodeID='+NodeID+'&startdatetime='+startdatetime, function(data){ const parsed = JSON.parse(data)...... so what I'm getting out of this is that the data returning will get parsed out to being currentTemp and currentHumidity ?
currentTemp and currentHumidity are the values returned from the server.
Good Sir, I will be testing this but I think you are the winner
and those values will be available within the <script> /....</script> ?
No. there are available within that call back function only. (Because of closures). If you need to make it as global, assign them to window.currentTemp = parsed.currentTemp
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.