Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multipart post request with d3.json()/d3.xhr()

Tags:

json

d3.js

Is there currently no support for submitting multipart form data with a request?

I understand how to perform a POST with d3.json().post() as described here, but I wanted to use POST to submit parameters to an API via multipart/form-data.

It seems strange that I can not find any resources on how best to do this; the closest I have come is https://github.com/mbostock/d3/issues/929 and https://github.com/mbostock/d3/wiki/Requests but these do not really cover multipart forms.

Is there an undocumented part of the functionality described in #929 that I couldn't find in d3.v3.js which would allow for use of multipart forms? Is anyone currently working on or interested in this issue?

like image 912
hushedfeet Avatar asked Oct 22 '22 22:10

hushedfeet


1 Answers

There are three steps to a successful multipart post.

  1. Add the header Content-type: application/x-www-form-urlencoded
  2. Encode the form data
  3. Concatenate it as if you were specifying query strings in a URL

Then just send it as the POST data.

None of this is specific to d3, but I thought I'd give my answer and some sample code, since I landed here.

Sample code:

var xhr = d3.xhr(post_url)
    .header("Content-type", "application/x-www-form-urlencoded");

xhr.post("arg1=" + encodeURIComponent(arg1) + "&arg2=" + encodeURIComponent(arg2),
  function(error, result) {
    if(error)
        throw new Error(error);
    read_paths.data(JSON.parse(result.responseText));
});
like image 83
Gordon Avatar answered Oct 25 '22 17:10

Gordon