1

I'm appending data from a list of <li>'s to a FormData object with:

media_links_array = [];
$('.media_links_ul:first li').each(function () {
    var media_type = $(this).attr("data-media_type");
    var media_link = $(this).text();
    var myObject = {
        "media_type": media_type,
        "media_link": media_link
    }
    media_links_array.push(myObject);
});
myFormData.append("media_links", media_links_array);

Expected Behaviour

I expected it to send (in Firebug Net > POST) as:

--------------- nnnnnnnnn Content-Disposition: form-data; name="media_links" 

{"media_type":media_type,"media_link":media_link}

Current Behaviour

But it is sending as:

--------------- nnnnnnnnn Content-Disposition: form-data; name="media_links" 

[object Object],[object Object]
Jason P
  • 26,608
  • 3
  • 29
  • 44
user1063287
  • 8,524
  • 19
  • 95
  • 183
  • Because that is what happens when toString() is applied. – epascarello Feb 24 '14 at 20:11
  • FormData.append expects a string file or blob to be it's second parameter. You gave it an array which is none of those things... https://developer.mozilla.org/en-US/docs/Web/API/FormData – Kevin B Feb 24 '14 at 20:12
  • And why would you need a formData object for this, it's just two strings you're trying to send to the server, surely there are easier ways to do that, as in jQuery.ajax ? – adeneo Feb 24 '14 at 20:15

1 Answers1

0

JSON.stringify(media_links_array) will give you your JSON object as a string.

Jason P
  • 26,608
  • 3
  • 29
  • 44
milagvoniduak
  • 3,064
  • 1
  • 16
  • 17
  • 1
    note: this doesn't work with some browsers (http://caniuse.com/json), A-grade browsers are fine, but if you need to support something like IE7 or lower, then you'll need a polyfill (http://bestiejs.github.io/json3/) – Populus Feb 24 '14 at 20:17
  • 1
    @Populus Right, but that's also a concern for FormData. If we can assume FormData exists, we can also assume JSON.stringify does. – Kevin B Feb 24 '14 at 20:20
  • Thanks very much, and for additional info. – user1063287 Feb 24 '14 at 20:25
  • And just for follow up, on server side in Python to get it back to an array: `media_links = request.forms.media_links media_links = ast.literal_eval(media_links)` from http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python – user1063287 Feb 24 '14 at 20:41