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

Community
  • 1
  • 1
Nebelhom
  • 3,783
  • 4
  • 21
  • 22
  • I have made an answer for the same question [here](https://stackoverflow.com/questions/23889107/sending-array-data-with-jquery-and-flask/40951200#40951200) – joseph Dec 03 '16 at 18:55

1 Answers1

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.

Thomas N.
  • 548
  • 5
  • 12
  • 3
    [`$.post(endpoint, {wordlist: list}, null, 'json').then(successHandler)`](http://api.jquery.com/jQuery.post/) would also work, but you would need to pull from [`request.form.getlist('wordlist')`](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict.getlist). On the other hand, there would be no need for `json.loads`. – Sean Vieira May 30 '14 at 16:25
  • 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 – Nebelhom May 31 '14 at 06:57
  • I think Sean's answer is the cleanest. No need to manually serialize/deserialize. Let's Flask handle the work. – jds Aug 13 '15 at 16:47
  • 2
    The answer of Sean works for me using `request.form.getlist('wordlist[]')` – Erwan Aug 25 '16 at 12:54