Home > Back-end >  Passing ajax-requested data into Python function
Passing ajax-requested data into Python function

Time:11-06

The Flask application below makes Ajax calls indefinitely to a back-end index function which queries a data base and injects result to template.

I'm expecting that, after Ajax is finished, the injected data will be refreshed hence updating the plot but it's not.

How to update Ajax in a way that refreshes the injected data into 'index.html' (hence updating plot which consumes that data)?

Appreciate your help!

HTML code:

<div class="card-body">
    <div  class="chart-area">
       <div id = 'load' class = 'chart' style = 'height:100%'></div> <!--This is where chart appears -->
     </div>
   </div>

JQuery code:

<script> 
    $(document).ready(function(){

        function ajaxCall(){

            $.ajax({
                async: false,
                type: 'POST',
                url: '/',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                success: function (data) {
                  ??? perhaps something here???
                    }
            });

        }

    setInterval(ajaxCall, 2000); // repeatedly calls ajaxCall()

    var graphs = {{graphJSON | safe}}; // saves injected data to variable

    Plotly.plot('load',graphs,{}); // passes saved variable to Python function for plotting which then appears in div with 'load' id above.

    });
</script>

Flask code:

from flask import render_template, Blueprint,  
from App.functions.reddit_streamer import AWS_RDB
import json
import plotly
import plotly.express as px



core = Blueprint('core', __name__)



@core.route('/', methods = ['GET', 'POST'])
def index():

    db = AWS_RDB()

    df = db.query_half_hour()

    fig = px.line(df.loc[1:,:], x = 'date' , y = '# of comments')

    graphJSON = json.dumps(fig, cls = plotly.utils.PlotlyJSONEncoder)

    return render_template('index.html', graphJSON = graphJSON)

CodePudding user response:

A simple example of querying and displaying data for plotly via ajax at periodic intervals.

I have created another route that provides the data in JSON format. Then I use the Fetch API to query the data, which is then used to update the graph. An implementation with jQuery would also be conceivable.

from flask import Flask
from flask import make_response, render_template
import json, random
import pandas as pd
import plotly
import plotly.express as px

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/data')
def data():
    df = pd.DataFrame({
        'Year': ['2012', '2014', '2016', '2018', '2020', '2022'],
        'Amount': [random.randint(0, 10) for _ in range(6)],
    })

    fig = px.line(df, x='Year', y='Amount')
    dat = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    resp = make_response(dat)
    resp.mimetype = 'application/json'
    return resp
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="chart" class="chart"></div>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script type="text/javascript">
      (() => {
        const update = () => {
          fetch('/data')
            .then(resp => resp.json())
            .then(data => Plotly.react('chart', data, {}));
        };
        update();
        setInterval(update, 2000);
      })();
    </script>
  </body>
</html>
  • Related