Using Ajax and Endpoints to Send/Retrieve Data From Flask

Ajax is a methodology to communicate with a server asynchronously without having to reload the page. This methodology is instrumental in sending new data to update the webpage, but you don't want to refresh to get new content, which can be an issue if you're using the Flask framework.


In Python, you have an array of data you want to send to the front end. Using Flask, you can use jsonify to serialize the data into JSON format, which can be used as a response type. In Flask, your response types can render pages or redirect to a webpage or a route specified in the app, but in this case, we only want to return a JSON object.


In the example below, "thepackage" is the name the data will be associated with. To add more variables to return, expand the number of elements inside.

@app.route('/get_information')
def get_information():
    account_info = [
        "some_data_1",
        "some_data_2",
        "some_data_3",
        "some_data_4",
        "some_data_5",  
    ]

    return jsonify(
        thepackage=account_info
    )

Getting data from the front end

In a script or .JS file:

<script type=text/javascript> 
function GetAccount() {
  $.ajax({
    url: "/get_information",
    type: "get",
    success: function(response) {
      var account_package = data.thepackage;
       // Do something with your data 
    },
    error: function(xhr) {
      // Uh-oh, something went wrong.
    }
  });
</script>
<button onclick="GetAccount()">Get data</button>
 

Using AJAX, you can formulate a get request by specifying the target url, and on success, the data from your python script will be wrapped in a JSON object.

Sending data to backend and getting a response

Like a normal CURL request, you can send data. Modify your AJAX script by adding a data parameter.

<script type=text/javascript> 
function GetAccount(account_email) {
  $.ajax({
    url: "/get_information",
    type: "get",
    data: {some_data: account_email},
    success: function(response) {
      var account_package = data.thepackage;
       // Do something with your data 
    },
    error: function(xhr) {
      // Uh-oh, something went wrong.
    }
  });
</script>
<button onclick="GetAccount('john.smith@example.com')">Get data</button>

Back in your python, you can retrieve the arument using Flask's request function.

email_to_delete = request.args.get('some_data')

Using endpoints to send data

Alternatively, you can send data to your backend using endpoints. The following are two examples of that working.

@app.route('/test/key=<key>/user=<id>')
def test_echo(key, id):
    print("ID: " + id)
    print("key: " + key)
    return render_template(
        'index.html')


# /new_reg?arg1=test&arg2=testing
@app.route("/new_reg", methods=['GET', 'POST'])
def create_registration():
    test = request.args.get('arg1')
    print(test)
    return render_template(
        'index.html')

 

These are all things I wish I knew right off the bat when I first started building web apps.