D3.js – Requests API


D3.js – Requests API


”;


D3.js provides a request API to perform the XMLHttpRequest. This chapter explains the various requests API in detail.

XMLHttpRequest

XMLHttpRequest is the built-in http client to emulate the browser XMLHttpRequest object. It can be used with JS designed for browsers to improve reuse of code and allow the use of existing libraries.

You can include the module in your project and use as the browser-based XHR object as explained below.

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

It supports both async and synchronous requests and it performs GET, POST, PUT, and DELETE requests.

Configuring Requests

You can load directly from “d3js.org” using the script below.

<script src = "https://d3js.org/d3-request.v1.min.js"></script>
<script>
   d3.json("/path/to/sample.json", callback);
</script>

Here, the requests API have built-in support for parsing JSON, CSV and TSV. You can parse additional formats by using the request or text directly.

Load Text Files

To load a text file, use the following syntax.

d3.text("/path/to/sample.txt", function(error, text) {
   if (error) throw error;
   console.log(text); 
});

Parsing CSV files

To load and parse a CSV file, use the following syntax.

d3.csv("/path/to/sample.csv", function(error, data) {
   if (error) throw error;
   console.log(data); 
});

Similarly, you can load the JSON and TSV files as well.

Working Example

Let us go through a simple example for how to load and parse a CSV file. Before that, you need to create a CSV file named “sample.csv” in your d3 application folder as shown below.

Num1,Num2
1,2
3,4
5,6
7,8
9,10

Now, create a webpage “requests.html” using the following script.

<!DOCTYPE html>
<html>
   <head>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <h3> D3.js Requests API </h3>
      <script>
         d3.csv("sample.csv", function(data) {
            console.log(data); 
         });
      </script>
   </body>
</html>

Now, request the browser and you will see the following response,