0
votes

I'm developing an app, in which I use jqPlot to plot a pie chart using some data retrieved via AJAX. However, I've noted that the resulting pie chart is wrong. When I manually put the data in an array, the pie chart is correct.

This is part of my code.

  $.ajax({
    url:'http://localhost/mijson.php',
    dataType:'json',
    async:false,
    success:function(data){
        for(a in data){
            var div_pintar = "<div id='divgrafica"+a+"' class='myChart'></div>";
            $("#espacio_graficas").append(div_pintar);
            var datos_tmp = [];
            datos_tmp.push(['Ok',data[a]['ok']]);
            datos_tmp.push(['Fail',data[a]['fail']]);

            $.jqplot('divgrafica'+a, [datos_tmp], {
                title:data[a]['label'] ,
                seriesDefaults:{
                    renderer:$.jqplot.PieRenderer,
                    trendline:{ show: true },
                },
                legend:{ show: true }
            });
            ...

The JSON that I get is this:

[{"label":"FECHA","requer":56,"ok":28,"fail":28},
 {"label":"TTM Y FECHA","requer":35,"ok":8,"fail":27}]

In summary, it shows me a pie chart, for example, with two values, but add is 14%.

The same occurs if I use ajaxDataRenderer:

...
    plo12 = $.jqplot('pieChart2', jsonurl,{
        title: 'AJAX JSON Data Renderer',
        dataRenderer: ajaxDataRenderer,
        seriesDefaults: {
            renderer: $.jqplot.PieRenderer,
            rendererOptions: {
                showDataLabels: true
            }
        },
        legend: { show: true, location: 'e' }
    });
    ...
2
Your description of what you see wrong is unclear. Please provide screen shots of the incorrect plot (using AJAX data) and the correct plot (using manually inserted data). Please provide the code you use to plot the pie chart when you have "manually put the data in an array" (so we can see how you are inserting it and plotting the data, because having two different results implies that you are doing this differently than the JSON is being received via AJAX). - Makyen

2 Answers

1
votes

Without more information it is difficult to determine what your problem is exactly.

However, the most obvious thing that would result in erroneous charts is the use of:

for(a in data){

to parse the JSON object, which is actually an array, that has been returned by the AJAX success:function:

$.ajax({
    success:function(data){

To quote the "for...in" page on MDN:

Array iteration and for...in
Note: for..in should not be used to iterate over an Array where index order is important.

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the for...of loop) when iterating over arrays where the order of access is important.

Order is important in this instance because you should desire the presentation of the charts to be in the same order no matter the browser being used. Thus, you should process the members of the array in a deterministic manner.

More importantly:

Iterating over own properties only

If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames or perform a hasOwnProperty check (propertyIsEnumerable can also be used). Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method.

Each array has properties which are associated with its prototype instead of just the members of the array. Including these in your processing, by use of the for(a in data){}, without any qualification, is almost guaranteed to result in an erroneous display.

One alternate method to code what you have is to use forEach():

  $.ajax({
    url:'http://localhost/mijson.php',
    dataType:'json',
    async:false,
    success:function(data){
        data.forEach(function(curObject, a) {
            var div_pintar = "<div id='divgrafica"+a+"' class='myChart'></div>";
            $("#espacio_graficas").append(div_pintar);
            var datos_tmp = [];
            datos_tmp.push(['Ok',data[a]['ok']]);
            datos_tmp.push(['Fail',data[a]['fail']]);

            $.jqplot('divgrafica'+a, [datos_tmp], {
                title:data[a]['label'] ,
                seriesDefaults:{
                    renderer:$.jqplot.PieRenderer,
                    trendline:{ show: true },
                },
                legend:{ show: true }
            });
            ...

Note: I would normally change all the data[a] references to curObject, but not doing so will work (the array index is passed in as a) and results in the least amount of changes to your code. Making the additional changes should make the code slightly faster due to not having to do the array look-up multiple times.

With those changes and using the more descriptive index instead of a, the code looks like:

  $.ajax({
    url:'http://localhost/mijson.php',
    dataType:'json',
    async:false,
    success:function(data){
        data.forEach(function(curObject, index) {
            var div_pintar = "<div id='divgrafica"+index+"' class='myChart'></div>";
            $("#espacio_graficas").append(div_pintar);
            var datos_tmp = [];
            datos_tmp.push(['Ok',curObject['ok']]);
            datos_tmp.push(['Fail',curObject['fail']]);

            $.jqplot('divgrafica'+index, [datos_tmp], {
                title:curObject['label'] ,
                seriesDefaults:{
                    renderer:$.jqplot.PieRenderer,
                    trendline:{ show: true },
                },
                legend:{ show: true }
            });
            ...
1
votes

Thanks to Makyen who help me, although his answer is good, errors still persist. After more 16 hours trying, i found solution, that was very, very easy.

 .....
     var div_pintar = "<div id='divgrafica"+index+"' class='myChart'></div>";
                $("#espacio_graficas").append(div_pintar);
                var datos_tmp = [];
                    datos_tmp.push(['Ok',parseInt(datos[a]['ok'])]);
                    datos_tmp.push(['Fail',parseInt(datos[a]['fail'])]);
    ......

Only with function from javascript parseInt

I hope this can help to other persons. I lost many hours :(