Python Forum

Full Version: [Flask]Ajax in Flask
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
A look at using Ajax in Flask.
Quote:AJAX is a developer's dream, because you can:
  • Update a web page without reloading the page
  • Request data from a server - after the page has loaded
  • Receive data from a server - after the page has loaded
  • Send data to a server - in the background
On the server-side we have a Python function that return a random language from a list.
lst = ["Python", 'HTML', 'JavaScript', 'CSS']
All communication is in Json format,function is returning value with Flask jsonify()
On the client-side jQuery getJSON() which do a Ajax call to the function.

Here a Pen skeleton of how it look,
button when push will get value from the Python function.

Setup style.css is unchanged copy from Pen.
Folders.
language\
app.py
  templates\
  index.html
  static\
    css\
    style.css
app.py
from flask import Flask, render_template, jsonify
import random

app = Flask(__name__)
@app.route('/')
def foo():
    return render_template("index.html")

@app.route('/get_word')
def languages():
    '''Return data in json format'''
    lst = ["Python", 'HTML', 'JavaScript', 'CSS']
    words = {}
    words['choice'] = random.choice(lst)
    return jsonify(words)

if __name__ == '__main__':
    app.run(debug=True)
index.html
<!doctype html>
<html>
  <head>
    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}" />
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
  </head>

  <script type="text/javascript">
    $(document).ready(function() {
      $("#get_data").click(function() {
        $.getJSON('/get_word', function(dat) {
          $("#language").text(dat['choice']);
        });
      });
    });
  </script>

  <div class='all'>
    <div class="parent">
      <h1>Ajax call</h1>
      <div class="one">
        <button id='get_data'>Language</button>
      </div>
      <div class="two">
        <a id="language">Get Language</a>
      </div>
    </div>
  </div>
</html>
Run python app.py
In Browser http://127.0.0.1:5000/
Hello!
There is AJAX extension for Flask.

Here are some other Flask extensions you can find useful.
(Sep-29-2016, 12:26 PM)wavic Wrote: [ -> ]Hello!
There is AJAX extension for Flask.

Here are some other Flask extensions you can find useful.
Yes,i know this.
I find using jQuery direct to be cleaner in many cases,
if there are not so many Ajax call.
There are some setup work to do when using Sijax.