Rubaninferno
Rubaninferno

Reputation: 65

Unable to send an array of objects to flask using JSON & AJAX

I am getting an empty [ ] when i hit generate:

127.0.0.1 - - [18/Oct/2019 01:04:37] "POST / HTTP/1.1" 200 - []

Here's the array & JSON in JS:


    var List = [
        { load: "2", location: "3" },
        { load: "2", location: "4" },
        { load: "2", location: "8" },
        ];

    document.querySelector('#generate').addEventListener('click',function() {
        var json_list = JSON.stringify(List)
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/",
            traditional: "true",
            data: json_list,
            dataType: "json"
            });

    })

And here is the code in Flask:


    @app.route('/',methods =['GET','POST'])
    def index():
        req = request.get_json()

        print(req)
        return render_template("index.html")

However, if i send a array of just numbers, no objects inside (eg. [2,3,4,5]) I actually get the array on my python terminal. So what should I add for the objects to go through?

Edit: When I jsonify the input in flask i get: Response 86 bytes [200 OK]

Upvotes: 0

Views: 2472

Answers (1)

v25
v25

Reputation: 7656

This could be achieved with the fetch API (see supported browsers) which doesn't depend on Jquery.

Based on this other useful answer you could have a template at templates/index.html:

<html>
<body>
<button type="button" id='generate'>Click Me!</button> 

  <script type='text/javascript'>
    var List = [
      { load: "2", location: "3" },
      { load: "2", location: "4" },
      { load: "2", location: "8" },
      ];

    document.getElementById('generate').addEventListener('click', event => {

    fetch("/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(List)
      }).then(res => {
        console.log("Request complete! response:", res);
      });
    });

  </script>
</body>
</html>

The flask file should look like this:

from flask import Flask , request, render_template, jsonify
app = Flask(__name__)

@app.route('/',methods =['GET','POST'])
def index():
    if request.method == 'POST':
        req = request.get_json()
        print(req)
        return jsonify({'status':'success'})

    else:
        return render_template('index.html')

if __name__=='__main__':
    app.run(host='0.0.0.0')

Notice that this also handles logic based on the request method:

  • POST request will print the json payload (req) to the server console, then return a response using Flask's jsonify function.
  • Any other request will render the templates/index.html template. (display the UI with buttons to the user)

When you click the button in the interface, you see this at the server console:

[{'load': '2', 'location': '3'}, {'load': '2', 'location': '4'}, {'load': '2', 'location': '8'}]

Upvotes: 1

Related Questions