Hasunohana
Hasunohana

Reputation: 615

Why does Flask is receiving this variable as unicode but not as array?

I trying to send an array by Post Method using Jquery.

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

var url = "{{url_for('page')}}";
post_to_url(url,{'data':arrayObj}, "post");

Until here, when I use console.log($.type(arrayObj)), is returning me an array.

@mod.route('/page',methods=["POST","GET"])
def page():
 if request.method=="POST":
  import pdb; pdb.set_trace()
  d = request.form['data']
  return render_template('testing/page.html',data=d)
 return render_template('testing/page.html')

Using PDB, type(d) the variable is returning an unicode. Why?

Upvotes: 0

Views: 95

Answers (1)

wmorrell
wmorrell

Reputation: 5307

params has a single key. The for loop is executed once, and this line:

hiddenField.setAttribute("value", params[key]);

… is setting the hidden field value to the array serialized to a string.

If you know all your keys are array objects, just loop over the values and insert multiple input elements:

for (let key in params) {
    if (params.hasOwnProperty(key)) {
        let values = params[key];
        for (let value of values) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", value);
            form.appendChild(hiddenField);
        }
    }
}

If you don't know all your keys are arrays, you can change the backend code to split incoming values on comma. Note this will break for any values that literally contain ,.

@mod.route('/page',methods=["POST","GET"])
def page():
 if request.method=="POST":
  d = request.form['data']
  d_array = d.split(',')
  return render_template('testing/page.html',data=d_array)
 return render_template('testing/page.html')

Upvotes: 1

Related Questions