Pregunta

¡Estoy atascado!

Necesito crear HighChart con el resultado JSON. Encontré algunas fuentes aquí, pero no puedo poner esto a trabajar.

Lo más cerca que puedo conseguir fue hacer esto:

Opciones de gráfico:

var options = {
    chart: {
        renderTo: 'tudo',
        defaultSeriesType: 'column',
        rightMargin: 80
    },

    title: {
        text: 'Weekdays'
    },
    subtitle: {
        text: 'Source: somewhere in a calendar'
    },

     xAxis: {
        labels: {
            enabled: false
    }
    },

    yAxis: [
        {
            min: 0,
            title: {
                text: 'Amount'
             }
        },
        {
            linkedTo: 0,
            opposite: true
        }
    ],

    series: []
};

Ajax llame:

$.getJSON('ajax/calc.ajax.php', function(data) {

        var series = [];

        $.each(data, function(key, value) {

            series.name = key;
            series.data = value;

            options.series.push(name);
        });

        var chart = new Highcharts.Chart(options);  
});

HighChart carga bien y llena la serie con Series 1, Series 2 ....

Pero no se hace gráfico, él se mantiene en blanco. ( algo como esto: Manifestación).

Quiero saber si me estoy perdiendo algo o todo.

Gracias

ACTUALIZACIÓN: Cambio el SQL, ahora estoy trabajando con 2 campos, y con esto, el trabajo GRAFIC perfecto, ahora solo quiero saber si hacer así está bien.

header('Content-Type: application/json');

        while(!$res->EOF){

            //$json = array("group" => "Web", "action" => "list");
            $json[$res->fields["DESMAR"]] = array(intval($res->fields["QTD"]));
            //$json["users"] = array(array("name" => "JulioGreff", "status" => "online"));
            $res->MoveNext();
        }

        echo json_encode($json);
¿Fue útil?

Solución

En tus AJAX Llamada -

$.getJSON('ajax/calc.ajax.php', function(data) {
    var series = []; // <---------------------- must be object not array
    $.each(data, function(key, value) {
        series.name = key;
        series.data = value;
        options.series.push(name); // <-------- it should be series not name
    });
    var chart = new Highcharts.Chart(options);  
});

Entonces, sería el siguiente -

$.getJSON('ajax/calc.ajax.php', function(data) {        
    $.each(data, function(key, value) {
        var series = {}; // <-------------------- moved and changed to object
        series.name = key;
        series.data = value;
        options.series.push(series); // <-------- pushing series object
    });
    var chart = new Highcharts.Chart(options);  
});

Además, considerando el JSON que está recibiendo -

{"NOME": "Transformador 250VA 0-230-380V / 0,24V-0-48V", "MODOLO": "Transformador", "Marca": "Seit", "Valor": "318.87 | 542.08", ",", ", Qtdade ":" 0 "??}

lo que estas haciendo en el $.each -

series.data = value;

No tiene sentido.

serie. Data es una matriz. Entonces, podría parecer o como sigue -

[y1, y2, y3, ....] // array of numbers (which are y values)

o como sigue -

[[x1, y1], [x2, y2], [x3, y3], ....] // array of arrays of pair of numbers (x and y values)

o como sigue -

// array of objects which can have x and y values as properties
[{                       
    name: 'Point 1',
    color: '#00FF00',
    y: 0
}, {
    name: 'Point 2',
    color: '#FF00FF',
    y: 5
}]

Entonces, asegúrese de que su código PHP produzca un JSON que coincida con una matriz de uno de los anteriores, entonces series.data = value dentro de tu $.each trabajará.

Actualizar:Lo siento, hago Java y nunca he hecho PHP, así que no puedo ayudarte mucho con PHP. Pero, ¿puedes intentarlo con lo siguiente como tu PHP, solo para ver si aparece el gráfico?

header('Content-Type: application/json');
$return_data = array(
    array(array(10, 20), array(20, 30), array(56, 30), array(50, 20)),
    array(array(10, 0), array(20, 10), array(56, 100), array(50, 40))
);
echo json_encode($return_data);

Actualizar: Para representar el pastel mientras mantiene el mismo PHP.

$.getJSON('ajax/calc.ajax.php', function(data) {        
    var series = { // <-------------------- create just one series object
        type: 'pie',
        data: [] //data array for new series
    }; 
    $.each(data, function(key, value) {
        series.data.push([key, value[0]]);            
    });
    options.series.push(series); // <-------- pushing series object
    var chart = new Highcharts.Chart(options);  
});

Esto debería dibujar gráfico de pastel.

Otros consejos

Parece que el problema radica en su código PHP. HighCharts espera que siga una serie un formato particular. En su caso, las cosas funcionan (en parte) porque name es uno de los campos que está buscando. Los datos, sin embargo, deben estar en uno de los tres formatos:

  • Una variedad de valores y (por ejemplo [0, 1, 2])
  • Una matriz de matrices (valores x, y; por ejemplo [[0,0], [1,1], [2,2]])
  • Una variedad de objetos que se encuentran usando propiedades puntuales

Me gustaría el último formato, creo. Por ejemplo:

var series = [];
series.name = "series1";
series.data = {y: 10}; //very minimalistic example of the object format
options.series.push(name);

Para que su código funcione, es posible que deba cambiar el interior de su $.each funcionar a algo como esto:

$.each(data, function(key, value) {
    series.name = key;

    series.data = {
        y: value.property_you_are_interested_in
    };

    options.series.push(name);
});

... Por supuesto, si quisieras usar una de las otras formas, también sería bastante fácil:

//First form (array of y values)
var series = {};
series.data = [];
$.each(data, function(key, value) {
    series.name = key;
    series.data.push(value.property_you_are_interested_in);
});
options.series.push(series);

//Second form (array of x, y values)
var series = {};
series.data = [];
$.each(data, function(key, value) {
    series.name = key;
    series.data.push([value.X_property_you_are_interested_in, value.Y_property_you_are_interested_in]);
});
options.series.push(series);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top