9

I am trying to get the flask/jquery/ajax example working for my specific case, but I am coming up short every time. I am aware this sort of question has been asked several times, but the answers do not help me (Yes, I am new to this).

The example passes a string from javascript to python. I would like to pass an array over. The web suggests that this is possible. Here is what I have:

HTML/Flask Template:

{% extends "layout.html" %}
{% block title %}Test{% endblock %}
{% block content %}
    <div>
      <h1>Flask Jquery Test</h1>
      <div>
        <input type="button" value="Transfer" id="button" />
      </div>
      <div>
        Wordlist<br />
        <select multiple="multiple" id="wordlist" size="5">
            <option>Volvo</option>
            <option>Audi</option>
            <option>BMW</option>
            <option>Mercedes</option>
            <option>Toyota</option>
        </select>
        <span id="result"></span>
      </div>
    </div>
{% endblock %}

JS Script:

$(document).ready(function() {
    $("#button").bind('click', function(){
        //Get all words from list
        var list = [];
        $("#wordlist option").each(function(){
            list.push($(this).val());
        });
        //var list = $( "#wordlist option" ).val();
        console.log(list);
        $.getJSON($SCRIPT_ROOT + '/_array2python', {
            wordlist: list.toString()
        }, function(data){
            console.log(data.result)
            $( "#result" ).text(data.result);
        });
        return false;
    });
});

Python:

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

@app.route('/_array2python')
def array2python():
    wordlist = request.args.get('wordlist', [])
    return jsonify(result=wordlist)

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404

Now, when passing into the list variable a string (e.g. var list = $( "#wordlist option" ).val(); ), this code works just fine. However, when trying it with an array, it only ever passes the backup value (i.e. []).

Does this mean, I can only pass strings to python? How would I best pass a javascript array to python?

Thanks everyone for your help!

P.S. Maybe it is important to mention. I am using google app engine to host this code.

=================================================================================

FYI, these are the SO sites that I tried to follow and they did not help me:

Passing Javascript Array to Flask (Excellent and very detailed answer, but can't get it to work)

Passing data from javascript into Flask

Return data from html/js to python

1
  • I have made an answer for the same question here Commented Dec 3, 2016 at 18:55

1 Answer 1

15

Here is another way to pass JS Array to python :

JS Side:

$.getJSON($SCRIPT_ROOT + '/_array2python', {
        wordlist: JSON.stringify(list)
    }, function(data){
        console.log(data.result)
        $( "#result" ).text(data.result);
    });

Python Side:

import json

@app.route('/_array2python')
def array2python():
    wordlist = json.loads(request.args.get('wordlist'))
    # do some stuff
    return jsonify(result=wordlist)

As far as I know, strings are the only way to pass array from client to server.

Sign up to request clarification or add additional context in comments.

4 Comments

$.post(endpoint, {wordlist: list}, null, 'json').then(successHandler) would also work, but you would need to pull from request.form.getlist('wordlist'). On the other hand, there would be no need for json.loads.
Amazing, what a small diffference like adding json.loads can do to the code. I already suspected that only strings can be passed, but this makes version makes this a little less painful ;). Thx @Thomas N
I think Sean's answer is the cleanest. No need to manually serialize/deserialize. Let's Flask handle the work.
The answer of Sean works for me using request.form.getlist('wordlist[]')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.