Question

I'm trying to generate a pie graph with Sparklines but I'm running into some trouble. I can't seem to figure out what I'm doing wrong, but I feel it is a silly mistake.

I'm using the following code to generate a sparkline chart in the div #traffic_bos_ss:

//Display Visitor Screen Size Stats
$.getJSON('models/ucp/traffic/traffic_display_bos.php',
{   
    type: 'ss',
    server: server,
    api: api,
    ip: ip,
},
function(data)
{
    var values = data.views;
    //alert(values); 


    $('#traffic_bos_ss').sparkline(values,
    {
        type: "pie",
        height: "100%",
        tooltipFormat: 'data.screen - {{value}}',

    });
});

The JSON string fetched:

{"screen":"1220x1080, 1620x1080, 1920x1080","views":"[2, 2, 61]"}

For some reason Sparklines does not process the variable values. When I alert the variable it outputs "[2, 2, 61]". Now the jQuery code does work when I replace the snippet:

 var values = data.views;

with

 var values = [2, 2, 61];

What am I doing wrong?

Was it helpful?

Solution

You say that your call to getJSON is returning "views" which has a single string as its value:

"[2, 2, 61]"

However, when you change the code to:

var values = [2, 2, 61];

In this case you are correctly specifying an array of three integers.

Change your method which returns the JSON so that it correctly returns and array of integers for "views" instead of a single string i.e.

{"screen" : "1220x1080, 1620x1080, 1920x1080", "views": [2, 2, 61] }

See the jsFiddle here.

Also you say that your call to $.getJSON is working, but the method call you have written is not normal. See here for jQuery's getJSON documentation.

The following should work:

var values;
$.getJSON( "models/ucp/traffic/traffic_display_bos.php", function(data) {
  values = data.views;
});

$('#traffic_bos_ss').sparkline(values,
{
 type: "pie",
 height: "100%",
 tooltipFormat: 'data.screen - {{value}}'
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top