PraNisher
PraNisher

Reputation: 97

How do i get data from flask to my template using ajax?

I have some data in flask that I need to fetch and use in my template but the fetching should be done asynchronously using ajax and every 15 milliseconds.

Most of the solutions I have found are the other way around like from template to flask through ajax but I need the opposite.

@application.route('/test', methods=['GET','POST'])
def test():
  data = (some data i want to fetch every 15ms on test.html)
  return render_template('test.html', data=data)

Upvotes: 0

Views: 742

Answers (1)

zo0M
zo0M

Reputation: 1768

An asynchronous (or Ajax) request is similar to the routes and view functions that using templates, with the only difference that instead of returning HTML or a redirect, it just returns data, formatted as XML or more commonly JSON. Below you can see the example where returns the user info in JSON format:

On the server:

from flask import jsonify

@app.route('/ajax_example/<int:id>', methods=['GET'])
@login_required
def get_user(id):
    user = User.query.get_or_404(id)
    return jsonify(user)

On the client:

<script>
    $(function() {
        setInterval(function() {
            $.ajax('{{ url_for('main.get_user') }}).done(
                function(get_user_info) {
                    *blahblahblah*
                    }
            );
        }, 10000);
    });
</script>

Upvotes: 1

Related Questions