graphic with data from a REST service

Asked

Viewed 412 times

2

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

When consuming the API url in REST, I need to display the data in javascript-based graphics.

Does anyone know of a JS framework that manages graphics for a REST API and is free?

I can make an AJAX request, as in the example below, by playing the service url and handling the data in the graph.. as the example above.. based on the Example.. it is 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"}]
  • Take a look here by the site, looking for grafico: http://answall.com/search?q=grafico

  • i understand.. but I need one that has support to consume the service...

  • If you have a JSON I believe anyone can be easily adapted.

  • Okay... please take a look at my Dit’s question. It’s possible to?

  • Put an example of the return JSON format of your service.

  • ok... put the example

Show 1 more comment

2 answers

1


Since you did not specify 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>
<canvas id="myChart" width="250" height="100"></canvas>

  • What a show!... I’ll test it

  • a question... I am bringing my json through the angular... as I would put the json that comes through the Scope in the variable "json" that you created?

  • @beginner If I understand correctly it’s only you assign in the variable var json = $scope.json;, that would be it?

  • ok... but how would it be if json had more than one line?

  • ok... but how would isdso? I play the script inside the tag that has ng-Controller?

  • @beginner If you have more than one index you need to go through them all creating another for example https://jsfiddle.net/mnf1rveq/.

  • @beginner yes you can put in controller, see an example here. http://stackoverflow.com/questions/30267438/chart-js-angular

  • mass... can I write some text in the chart bar? i researched and it is something related to tooltip.. but I did not find anything exact

Show 3 more comments

0

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

Here the library link D3.

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

Example:

  1. Make your REST query and retrieve the result in JSON. That your code is already ok.
  2. Here you can follow 2 paths. Or save your JSON as a separate file to be read later or save your JSON to a variable to be read in the next process.
  3. Create the desired type of chart among the many that exist in D3.js by loading the D3.js library and pointing to your data. Be it in the file, be it the variable.

Thus:

//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>

// ************** Generate the tree diagram  *****************
var margin = {top: 20, right: 120, bottom: 20, left: 120},
    width = 960 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom;

var i = 0;

var tree = d3.layout.tree()
    .size([height, width]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = 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 taken from page

  • You can give an example of using D3 in this case?

  • exact.. can provide an example?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.