Daniel
Daniel

Reputation: 101

Python Flask + AJAX how to update div variable without reloading page

I have this example where I am trying to see if I have a record in my database to see whether or not this Triggered variable in my <div class="container-fluid"> is true or false. I have it that I can POST the page just fine but I am wondering if you could show me how I can get AJAX to constantly check if it has been triggered and change the variable Triggered inside that div without refreshing anything else.

HTML

**<div class="container-fluid" id="trigger-container">**
      <h1>Incubator Controller</h1>
        <div class="col-sm-4" style="background-color:lavender;"> 
          {% if Triggered == "True" %}
            <span class="badge badge-pill badge-success">ALL CLEAR</span>
          {% else %}
            <span class="badge badge-pill badge-danger">PROXIMITY ALERT</span>
          {% endif %}
        </div>

and the python flask side looks like this:

@app.route('/update', methods=['POST','GET'])
def Updater():
        Node = DAO.Pull_Node_Status(NodeID)
        Triggered= Node.Triggered[0]
        return render_template('Controller.html',Triggered=Triggered)

I know that I will need to use setInterval to call a javascript function.. but I am having a hard time piecing it together. This is the most simplest example that I can think of. I would like to be able to update multiple things constantly without refreshing the page and losing everything.

HTML script portion

<script>
    function UPDATETriggerDiv() { 
        $.get('/updateTrigger', 
            function(data){
                const parsed = JSON.parse(data)
                something to do here with (parsed.Triggered);
                g2.refresh(parsed.currentHumidity);
            };
        )
    };

    setInterval(function () {
            UPDATETriggerDiv();
            return false;
    }, 2500);
</script>

Any help would greatly be appreciated!

Upvotes: 0

Views: 574

Answers (1)

Musa
Musa

Reputation: 97672

If parsed.Triggered is boolean then you can set the Incubator Controller with an if/else statement.

var html = '<span class="badge badge-pill ';
if (parsed.Triggered){
    html += 'badge-success">ALL CLEAR</span>';
}
else{
    html += 'badge-danger">PROXIMITY ALERT</span>';
}
$("#trigger-container h1 + div").html(html);

Upvotes: 1

Related Questions