Saturday 31 July 2021

Using AJAX, JavaScript to call python flask function with return to JavaScript

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:

<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>

.....

<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:

@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("/tempnodeDHT", 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);


from Using AJAX, JavaScript to call python flask function with return to JavaScript

No comments:

Post a Comment