Grafico con chartjs

di FrancyFede il
11 risposte

Buonasera,

provavo con un semplicissimo array creato al volo a visualizzare il relativo grafico con chartjs. 

Vi posto il relativo errore che mi da e lo script per la creazione dell'array.

Grazie per chi mi da una mano a capire l'errore ed ad ottenere un risultato o con il mio array o con un vostro array di esempio.

errore:

Uncaught SyntaxError: Unexpected token '<' (at testChartjs.php:10:1)

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Test</title>
		<style>
			.chartBox {
				width: 700px;
			}
		</style> 
		 
	</head>
	<body>
		<?php
		$amonth = array(2000, 1500, 3000, 2850, 980, 4200);
		?>
		<div class="chartBox">
			<canvas id="myChart" ></canvas>
		</div>
		
		<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>	
				
		<script>
		
		// Setup block
		const amonth = <?php echo json_encode($amonth); ?>;
		const data = {
		labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
			datasets: {
				label: '# of Votes',
				//data: <?php echo json_encode($amount) ?>,
				data:  [12, 19, 3, 5, 2, 3],
				backgroundColor: [
					'rgba(255, 99, 132, 0.2)',
					'rgba(255, 159, 64, 0.2)',
					'rgba(255, 205, 86, 0.2)',
					'rgba(75, 192, 192, 0.2)',
					'rgba(54, 162, 235, 0.2)',
					'rgba(153, 102, 255, 0.2)',
					'rgba(201, 203, 207, 0.2)'
				],
				borderColor: [
					'rgb(255, 99, 132)',
					'rgb(255, 159, 64)',
					'rgb(255, 205, 86)',
					'rgb(75, 192, 192)',
					'rgb(54, 162, 235)',
					'rgb(153, 102, 255)',
					'rgb(201, 203, 207)'
				],
				borderWidth: 1
			}			
		};
		
		// Config block
		const config = {
			type: 'bar',
			data, 
			options: {
				scales: {
					y: {
						beginAtZero: true
					}
				}
			}
		};
		
		// Render block
		const myChart = new Chart(
		document.getElementById('myChart'),
		config	
		);
		</script>
	</body>
</html>

11 Risposte

  • Se modifichi con stringa racchiusa tra apici?

    const amonth = '<?php echo json_encode($amonth); ?>';
  • Grazie per il tuo suggerimento, MA non risolve il problema.

    Ho sempre il solito errore:

    Uncaught SyntaxError: Unexpected token '<' (at testChartjs.php:10:1)

    ma la cosa strana e che se visualizzo il dettaglio dell'errore, lo stesso viene evidenziato a riga 10 ovvero alla chiusura della parente graffa del CSS

    <style>
    	.chartBox {
    		width: 700px;
    	} // Uncaught SyntaxError: Unexpected token '<'
    </style> 
  • Ho tolto il NBSP UTF-8 , cambiato myChart in stringa nella dichiarazione della classe Chart e aggiunto tra parentesi quadre datasets e funziona.

    NBSP https://www.bigmessowires.com/2021/10/14/non-breaking-spaces-and-utf-8-madness/#:~:text=The%20direct%20UTF%2D8%20encoding,sequence%20for%20non%2Dbreaking%20space.

    prova ccosì

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Test</title>
            <style>
                .chartBox {
                    width: 700px;
                }
            </style>
            
        </head>
        <body>
            <?php
            $amonth = array(2000, 1500, 3000, 2850, 980, 4200);
            ?>
            <div class="chartBox">
                <canvas id="myChart" ></canvas>
            </div>
            
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>    
                    
            <script>
            
            // Setup block
            const amonth = <?php echo json_encode($amonth); ?>;
            const data = {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                datasets: [{
                    label: '# of Votes',
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(255, 159, 64, 0.2)',
                        'rgba(255, 205, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(201, 203, 207, 0.2)'
                    ],
                    borderColor: [
                        'rgb(255, 99, 132)',
                        'rgb(255, 159, 64)',
                        'rgb(255, 205, 86)',
                        'rgb(75, 192, 192)',
                        'rgb(54, 162, 235)',
                        'rgb(153, 102, 255)',
                        'rgb(201, 203, 207)'
                    ],
                    borderWidth: 1
                }]            
            };
            
            // Config block
            const config = {
                type: 'bar',
                data,
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            };
            
            // Render block
            const myChart = new Chart(
            "myChart",
            config    
            );
            </script>
        </body>
    </html>
  • 13/08/2023 - FrancyFede ha scritto:


    ma la cosa strana e che se visualizzo il dettaglio dell'errore, lo stesso viene evidenziato a riga 10 ovvero alla chiusura della parente graffa del CSS

    Analizza il codice sorgente della pagina all'interno del browser una volta che è stato restituito dal server per vedere in quale punto è presente il carattere indesiderato, o i caratteri se ce n'è più di uno.

  • Buongiorno,

    ok adesso va. Grazie a tutti e buon ferragosto.

    Francy

  • Buongiorno a tutti,

    riprendendo questa discussione, chiedo un vostro aiuto per come implementare il codice per visualizzare l'array con  2 valori.

    Mi spiego: ho un array ($mio_array) che contiene contemporaneamente una data (anno) , il corrispettivo importo per anno ealtre informazioni che al momento non mi servono.

    Carico, in un nuovo array ($dati_per_anno) le informazioni di mio interesse per poter visualizzare con il grafico.

    esempio:

    Anno Importo

    2021 13500

    2022 45000

    2023 36271

    vi posto il codice e mi spiegate come implementare / correggere lo stesso???

    Grazie

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Test</title>
            <style>
                .chartBox {
                    width: 700px;
                }
            </style>
            
        </head>
        <body>
            <?php
            $dati_per_anno = array();
    	
    		for ($b=0; $b<count($array02); $b++) {
    			$dati_per_anno[$b]['ANNO'] = $mio_array[$b]['ANNO']; 
    			$dati_per_anno[$b]['IMPORTO'] = $mio_array[$b]['IMPORTO']; 
    		}
    		
            ?>
            <div class="chartBox">
                <canvas id="myChart" ></canvas>
            </div>
            
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>    
                    
            <script>
            
            // Setup block
            const data = {
    		labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Green'],
    		datasets: [{
    				label: 'Test my first chart',
    				data: <?php echo json_encode(????); ?>,
    				options: {
    					animation: false
    				},
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(255, 159, 64, 0.2)',
                        'rgba(255, 205, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(201, 203, 207, 0.2)'
                    ],
                    borderColor: [
                        'rgb(255, 99, 132)',
                        'rgb(255, 159, 64)',
                        'rgb(255, 205, 86)',
                        'rgb(75, 192, 192)',
                        'rgb(54, 162, 235)',
                        'rgb(153, 102, 255)',
                        'rgb(201, 203, 207)'
                    ],
                    borderWidth: 1
                }]            
            };
            
            // Config block
            const config = {
                type: 'bar',
                data,
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            };
            
            // Render block
            const myChart = new Chart(
            "myChart",
            config    
            );
            </script>
        </body>
    </html>
  • Buongiorno,

    ho risolto il precedente quesito ma non riesco a capire come valorizzare la labels tra le parentesi quadre

    const revenue = <?php echo json_encode($dati_per_anno); ?>; 
    		const data = {
    			labels: ['2012', '2015', '2016', '2017', '2018', '2019', 'Green', 'ABC', '8', '9'],
    			datasets: [{
    					label: 'Importo rimborso: ',
    					data: revenue,
    					......
    					......

    ovvero questa porzione di codice:

    labels: ['2012', '2015', '2016', '2017', '2018', '2019', 'Green', 'ABC', '8', '9'],

    che deve essere sostituita con dei valori presenti in un nuovo array ($anno).

    vi posto il codice completo:

    <?php   
    	
    	$dati_per_anno = array();
    	$anno = array();
    	
    	for ($b=0; $b<count($mio_array); $b++) {
    		$dati_per_anno[] = $mio_array[$b]['IMPORTO']; 
    	}
    	
    	for ($c=0; $c<count($mio_array); $c++) {
    		$anno[] = $mio_array[$c]['ANNO'];
    	}
    	?>
    
    	<div class="chartBox1">
    		<canvas id="myChart" ></canvas>
    	</div>
    
    	<script>
    		const revenue = <?php echo json_encode($dati_per_anno); ?>; 
    		const data = {
    			labels: ['2012', '2015', '2016', '2017', '2018', '2019', 'Green', 'ABC', '8', '9'],
    			datasets: [{
    					label: 'Importo rimborso: ',
    					data: revenue,
    					options: {
    						animation: false
    					},
    					backgroundColor: [
    						'rgba(255, 99, 132, 0.2)',
    						'rgba(255, 159, 64, 0.2)',
    						'rgba(255, 205, 86, 0.2)',
    						'rgba(75, 192, 192, 0.2)',
    						'rgba(54, 162, 235, 0.2)',
    						'rgba(153, 102, 255, 0.2)',
    						'rgba(201, 203, 207, 0.2)'
    					],
    					borderColor: [
    						'rgb(255, 99, 132)',
    						'rgb(255, 159, 64)',
    						'rgb(255, 205, 86)',
    						'rgb(75, 192, 192)',
    						'rgb(54, 162, 235)',
    						'rgb(153, 102, 255)',
    						'rgb(201, 203, 207)'
    					],
    					borderWidth: 1
    				}],
    		};
    
    		// Config block
    		const config = {
    			type: 'bar',
    			data,
    			options: {
    				scales: {
    					y: {
    						beginAtZero: true
    					}
    				}
    			}
    		}
    
    		// Render block
    		const myChart = new Chart(
    		"myChart",
    		config
    		);
    	</script>
  • Perché non provi a usare json_encode() anche sull'array con gli anni da mostrare?

  • Ciao,

    mi spieghi meglio il tuo suggerimento? Grazie

    l'array e $anno

    <script>
    		const revenue = <?php echo json_encode($dati_per_anno); ?>; 
    		const data = {
    			labels: ['2012', '2015', '2016', '2017', '2018', '2019', 'Green', 'ABC', '8', '9'],
    			datasets: [{
  • 22/08/2023 - FrancyFede ha scritto:


    mi spieghi meglio il tuo suggerimento? Grazie

    La stessa cosa che hai scritto per impostare il valore di revenue, lo fai per il valore di labels.

    Per esemplificare:

    const revenue = <?php echo json_encode($dati_per_anno); ?>; 
    		const data = {
    			labels: <?php echo json_encode($anno); ?>,
    			datasets: [{

    Certo che questa “commistione” tra JSON e PHP è fastidiosa: a mio avviso conviene codificare la pagina in modo che postponga la generazione  del grafica e includa uno script che, in seguito, vada a scaricarsi tramite fetch() i dati in formato JSON prodotti sempre da una pagina PHP che fa solo quello.

    In pratica, invece di unire tutto nella stessa pagina, si fa una pagina senza dati con lo script che scarica questi dati da una pagina PHP che restituisce solo quelli.

    Chiaramente, è necessaria un po' di “fluidità” (ma neanche così tanta) nello scripting PHP.

    Se si agisce per codice preconfezionato o per scorciatoie, si arriva magari al risultato, ma la fatica e la manutenibilità di quel che si produce sono discutibili. :|

  • Provato e funziona.

    Condivido con te il far girare tutto con 2 script (php e javascript)

    Grazie

Devi accedere o registrarti per scrivere nel forum
11 risposte