Requests API in D3.js

Requests API in D3.js

In D3.js, we have the concept of request API that helps us to implement the XMLHttpRequest. In this lesson, we will discuss the different request APIs in a detailed manner.     

XMLHttpRequest

XMLHttpRequest is a built-in http client that is used to imitate the browser XMLHttpRequest. It will help you to use a browser (designed in JavaScript) to enhance the reutilization of the program code and also allow you to use the current libraries files.

You can easily add the module of XMLHttpRequest in the project and execute it as an XHR object, which is browser-based. It is explained below.

var XMLHtppRequest = require(“xmlhttprequest”). HttpRequest;
var xhr = new XMLHttpRequest();

The above-given script is able to implement the asynchronous and synchronous requests. It also manipulates the Put, Get, Post, and Delete requests.

Request API Configuration

You can configure the requests API from d3.js.org with the help of the following script.

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

The request API facilitates you to parse the CSV, TSV, and JSON files. You can also parse the added formats with the help of text or requests in a direct way.

Text Files Loading

The text files can be added by using the below-given script.

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

CSV Files Parsing/ Loading

You can parse and load the CSV files with the help of following script.

d3.csv("/path/to/example.csv", function(error, data)
{
            If (error) throw error;
            Console.log(data);
});

In the same manner, you can load the TSV and JSON files, as shown in the above- mentioned code.

Example

Here, we have discussed an example that will show you the parsing and loading of the csv files. First, you need to generate a CSV file named ‘example.csv’ as explained in the below- given code.

Num1, Num2

10, 11

12, 13

14, 15

16, 17

18, 19

Now, you are required to create an HTML file, as explained in the following script.

<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h2> Requests API in D3.js </h2>
<script>
         d3.csv("example.csv", function(data) {
            console.log(data);
         });
</script>
</body>
</html>

Output

After the successful execution of the code, you got the following output.

Methods of Request API

Some methods are listed below used in request API.

  • d3.request(url[, callback])
  • request.mimeType([type])
  • request.header(name[, value])
  • request.password([value])
  • request.user([value])
  • request.get([data])
  • request.timeout([timeout])
  • request.send(method[, data])
  • request.post([data])
  • d3.csv(url[[, row], callback])
  • request.abort()

Now, we will explain each method in detail.

d3.request(url[, callback])

This method can be applied to return a new request over an existing URL. If you specify a callback, then it returns an invoked request; otherwise request is not invoked as explained in below figure.

d3.request(url)
    .get(callback);
You can also use some following mentioned parameters for query.
d3.request(“/path/to/resource”)
     .header(“X-Requested-with”, “XMLHttpRequest”)
     .header(“content-type”, “application/x-www-form-urlencoded”)
     .post(“a  = 2&b = 3”, callback);

In the above code, if you want to specify the request header, then you need to define the constructor’s callback.

request.mimeType([type])

This method can be applied to allot the mime type for the values as explained in the below script.

d3.request(url)
    .mimeType(“text/csv”)
    .get(callback);

request.header(name[, value])

This method helps you to request the header name. If you don’t specify the value then it may discard the remove header along with the defined name. It is shown in below figure.

d3.request(url)
    .header(“Accept_language”, “en-US”)
    .header(“X-Requested-with”, “XMLHttepRequest”)
    .get(callback);

request.password([value])

It can be applied to fix a password for authentication purpose, if you define a value.

request.user([value])

This method will help you to allot a username for the user authentication. If you don’t declare a username, then it returns empty by default.    

request.get([data])

This method can be applied to send the request by using the Get() method as mentioned in the below given script.

request.send(“GET”, data, callback);

request.timeout([timeout])

It can be applied to fix the maximum timeout over a number of milliseconds, if you define a timeout.

request.send(method[, data])

This method will helps you to send the request with the help of provided Post() or Get() method.  

request.post([data])

This method can be applied to send the request by using the Post() method as mentioned in the below given script.

request.send(“POST”, data, callback);

d3.csv(url[[, row], callback])

It can be applied to return a request for csv file associated with the Uniform Resource Locator (URL) with mime type csv or text file. It is shown in the below given script.

d3.request(url)
    .mimeType(“text/csv”)
    .response(function(xhr)
{
            return d3.csvParse(xhr.responseText. row);
}); 

You can also define a callback with Post() method as explained following.

d3.request(url)
    .mimeType(“text/csv”)
    .response(function(xhr)
{
            return d3.csvParse(xhr.responseText. row);
})
    .post(callback);  

request.abort()

This method helps you to terminate the request.

Example

Here, we have an illustration to explain the request API method.

First, you need to create an HTML file named lang.csv in the root folder of the d3.js and make the below-given changes.

Year, Language, Author

1972, C, Dennis Ritchie

1995, Java, James Gosling

2011, D3js, Mike Bostock

Now, you are required to create a webpage name csv.html and associate it with the below- given example code.

<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h3> D3.js request API </h3>
<script>
         d3.csv("lang.csv", function(d) {
return {
               year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
               language: d.Language,
               author: d.Author,
};
},
function(error, rows)
{
console.log(error);
console.log(rows[0].year);
});
</script>
</body>
</html>

Output

After the successful execution of the above-mentioned code, you got the following output.