graph with data from a REST service

2

I have a REST service done in PHP and it returns me data in JSON .

When consuming the API url in REST, I need to display the data in graphs made in javascript.

Does anyone know of any framework in JS that generates graphs of a REST API and is free?

I can make a request in AJAX, as in the example below, by playing the service url and treating the data in the chart .. like the example above .. based on Example .. is it possible?

    $(document).ready(function () {
    //chama o ajax após a pagina ser carregada
    $.ajax({
        type: 'post',
        url: 'http://servico/dados',
        success: function (dados) {
            //gera o grafico
            var options = {
                responsive:true
            };
            var ctx = document.getElementById("GraficoBarra").getContext("2d");
            var BarChart = new Chart(ctx).Bar(dados, options);
        }
    });
});

edit:

json

[{"GERENCIA":10,"EMPRESA":"1","FILIAL":"1"}]
    
asked by anonymous 13.05.2016 / 15:47

2 answers

1

Since you have not specified any library, I leave an example using Chartjs :

var json = [{"GERENCIA":10,"EMPRESA":"1","FILIAL":"1"}];
json = json[0];//primeiro indice do JSON
var labels = [];//array com as labels
var dataChart = [];//para criar a série
for(i in json){//percorre o json e monta as labels e a série
	labels.push(i);
  dataChart.push(json[i]);
}
var data = {
    labels: labels,
    datasets: [
        {
            label: "Meus dados",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: dataChart,
        }
    ]
};

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data:data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script><canvasid="myChart" width="250" height="100"></canvas>
    
13.05.2016 / 17:31
0

It is very simple, after you recover your data in a JSON, you can send it to javascript D3. Can be using AJAX or not.

Here the library link D3 .

Note, in D3 the codes are already ready, just copy and paste. They are free.

Example:

  • Make your REST query and retrieve the result in JSON. This your code is already okay.
  • Here you can follow 2 paths. Either save your JSON as a separate file to read later or save your JSON to a variable to read in the next process.
  • Creates the desired chart type among many that exist in D3.js by loading the d3.js library and pointing to its data. Either in the file or in the file.
  • So:

    //Digamaos que esse é seu JSON, bem simples
    [
      {
      "name": "Top Level",
      "parent": "null",
      "children": [
        {
          "name": "Level 2: A",
          "parent": "Top Level",
          "children": [
            {
              "name": "Son of A",
              "parent": "Level 2: A"
            },
            {
              "name": "Daughter of A",
              "parent": "Level 2: A"
            }
          ]
        },
        {
          "name": "Level 2: B",
          "parent": "Top Level"
        }
      ]
    }
    ]
    
    //Esse vai ser o seu arquivo html ou php com javascript
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
    
        <title>Collapsible Tree Example</title>
    
        <style>
    
        .node circle {
          fill: #fff;
          stroke: steelblue;
          stroke-width: 3px;
        }
    
        .node text { font: 12px sans-serif; }
    
        .link {
          fill: none;
          stroke: #ccc;
          stroke-width: 2px;
        }
    
        </style>
    
      </head>
    
      <body>
    
    <!-- load the d3.js library --> 
    <script src="http://d3js.org/d3.v3.min.js"></script><script>//**************Generatethetreediagram*****************varmargin={top:20,right:120,bottom:20,left:120},width=960-margin.right-margin.left,height=500-margin.top-margin.bottom;vari=0;vartree=d3.layout.tree().size([height,width]);vardiagonal=d3.svg.diagonal().projection(function(d){return[d.y,d.x];});varsvg=d3.select("body").append("svg")
        .attr("width", width + margin.right + margin.left)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    
    // load the external data=======>Aqui vc está carregando de um arquivo externo usando o método d3.json.
    d3.json("treeData.json", function(error, treeData) {
      root = treeData[0];
      update(root);
    });
    
    function update(source) {
    
      // Compute the new tree layout.
      var nodes = tree.nodes(root).reverse(),
          links = tree.links(nodes);
    
      // Normalize for fixed-depth.
      nodes.forEach(function(d) { d.y = d.depth * 180; });
    
      // Declare the nodes…
      var node = svg.selectAll("g.node")
          .data(nodes, function(d) { return d.id || (d.id = ++i); });
    
      // Enter the nodes.
      var nodeEnter = node.enter().append("g")
          .attr("class", "node")
          .attr("transform", function(d) { 
              return "translate(" + d.y + "," + d.x + ")"; });
    
      nodeEnter.append("circle")
          .attr("r", 10)
          .style("fill", "#fff");
    
      nodeEnter.append("text")
          .attr("x", function(d) { 
              return d.children || d._children ? -13 : 13; })
          .attr("dy", ".35em")
          .attr("text-anchor", function(d) { 
              return d.children || d._children ? "end" : "start"; })
          .text(function(d) { return d.name; })
          .style("fill-opacity", 1);
    
      // Declare the links…
      var link = svg.selectAll("path.link")
          .data(links, function(d) { return d.target.id; });
    
      // Enter the links.
      link.enter().insert("path", "g")
          .attr("class", "link")
          .attr("d", diagonal);
    
    }
    
    </script>
    
      </body>
    </html>
    

    Example extracted from page

        
    13.05.2016 / 17:41