20

I'm using d3.json to get a dynamic data.

d3.json("/myweb/totalQtyService.do", function(json) {

    drawChart(json);
});

How do I post parameter on d3.json? i.e.

data : { year: "2012", customer: "type1“ }

Any idea pass those parameter on post? not url parameter /myweb/totalQtyService.do?year=2012&customer=type1

I tried such below, but couldn't make it work. because the data structure so different

d3.json => [Object, Object, Object, Object]

$.ajax => {entity_name: "ACTIVA"entity_tar_val: 350entity_val: 400level: 1_proto_: Object},...

$.ajax({ 
  type: "POST", 
  url: url,

  // parameter here
  data : {year: "2012", customer: "type1“},
  success: function(json){
       // console.log(json);
       **drawChart(json);**
  } ,
  error:function (request, err, ex) {
  }
 });
mruanova
  • 6,351
  • 6
  • 37
  • 55
yun
  • 235
  • 1
  • 3
  • 12

5 Answers5

24

NOTE: This answer applies to an older version of d3.json, see JoshuaTaylor's comment below.

NOTE for d3v5: The original answer is increasingly out of date. d3 v5 uses the fetch API and promises rather than XMLHttpRequest.

You can set the method of the http request in the second parameter of any of the d3-fetch data getting functions e.g.

d3.csv("/path/to/file.csv", { method: 'POST' })
    .then((data)=>{ /* do something with 'data' */ });

d3.json is a convenience method wrapping d3.xhr; it's hardwired to make GET requests.

If you want to POST you can use d3.xhr directly.

Something like this:

d3.xhr(url)
    .header("Content-Type", "application/json")
    .post(
        JSON.stringify({year: "2012", customer: "type1"}),
        function(err, rawData){
            var data = JSON.parse(rawData);
            console.log("got response", data);
        }
    );

Because no callback is specified in creation of the request object it's not sent immediately. Once received the JSON response can be parsed in the standard JavaScript way i.e. JSON.parse(data) The documentation for d3.xhr is here.

Tom P
  • 5,539
  • 1
  • 21
  • 24
  • The parameter list for the callback should be function(error, data). I submitted an edit. – anderspitman Aug 20 '14 at 23:08
  • Also you forgot to stringify the object into JSON – anderspitman Aug 20 '14 at 23:22
  • Thanks :). Personally, i find my original more understandable (callback arguments and stringification not withstanding). My aim was to give the smallest example of a generic XHR request leaving the handling of the response as a separate issue -- though I mentioned the most obvious way forward in the answer. Similarly I chose to explicitly split the example into two steps -- creation and execution of the request -- rather than chaining the two in a single expression in order to clarify the responsibility of each function call. Happy to accept the edit if people find them more helpful though. – Tom P Aug 21 '14 at 11:32
  • 8
    "d3.json is a convenience method wrapping d3.xhr; it's hardwired to make GET requests." This isn't true (at least now; perhaps it was in mid 2013). The documentation for d3.json says "If no callback is specified, the returned request can be issued using xhr.get or similar, and handled using xhr.on." This means that you can do `d3.json(url).post(data,callback)`. – Joshua Taylor Apr 19 '15 at 02:59
  • Yes, you're right -- at the time of writing d3.json used to return the response to the http request rather than the request object. Will update answer to reflect this change. – Tom P Apr 20 '15 at 14:49
10

You could also try this:

    d3.json(url,function(error, data) {
       ...
    })
   .header("Content-Type","application/json")
   .send("POST", JSON.stringify({year: "2012", customer: "type1"}));
FDaumas
  • 306
  • 3
  • 10
  • This appears to work but is incorrect. The d3.json(...) part immediately makes an HTTP get request - not what you want. The send then makes *another* call, this time the one you want. – Ian Fairman Nov 21 '16 at 11:39
4

Using d3-fetch in D3v5, it looks like

        d3.json(url, {
            method: 'POST',
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            },
            body: JSON.stringify(query)
        });

Where url is the URL and query is the content to post.

I found the answer in this question.

Gordon
  • 19,811
  • 4
  • 36
  • 74
0

If you want to make a request like an HTML form (using query parameters), then you would do:

d3.request("/path/to/resource")
.header("X-Requested-With", "XMLHttpRequest")
.header("Content-Type", "application/x-www-form-urlencoded")
.post("a=2&b=3", callback);

See the docs here: d3-request docs

If you want to convert a simple object to a query parameter string, then you can use the following function:

function obj2Params(params){
  var str = "";
  var amp = "";
  for(var p in params){
    if(params.hasOwnProperty(p)) {
        str += amp + encodeURIComponent(p) + "=" + encodeURIComponent(params[p]);
        amp = "&";
    }
  }
  return str;
}
juacala
  • 2,155
  • 1
  • 21
  • 22
  • For deep objects, see this link for how to build the query string: https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object – juacala May 24 '17 at 16:45
-1

If you use struts you can define the url and the parameter:

<s:url action="jsondatatreeaction" var="jsonsearchTag"
    namespace="/data">
    <s:param name="searchType" value="%{searchType}"></s:param>
</s:url>
. . . d3.json('${jsonsearchTag}', function(error, flare) { ... } . . .