Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
1  
$.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. –  Sean Vieira May 30 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 at 6:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.