Search code examples
javascriptphpexportcanvasjs

Save canvasJS charts to server directory


How could I save an exported canvasJS chart into server side directory using PHP?

There is no problem when creating a pie chart, making it exportable and exporting it directly using the built-in js function:

function ajaxGrafTarta(llamada,titulo){
    $.ajax({
        url: "dashboard.php",
        data: {
            llamada: llamada
        },
        type: "GET",
        dataType: "json",
        success: function (data) {
            var chart = new CanvasJS.Chart(llamada, {
                animationEnabled: true,
                exportEnabled: true,
                exportFileName: llamada,
                title: {
                    text: titulo
                },
                data: [{
                    type: "pie",
                    startAngle: -90,
                    yValueFormatString: "#,##0.00\"%\"",
                    indexLabel: "{label} ({y})",
                    dataPoints: data
                }]
            });
            chart.render();

            chart.exportChart({format: "jpg"});
        }
    });
}

My aim is to save that js-created file into a directory in my server (i know js is client-side), is it any way to do it?


Solution

  • For anyone facing this problem, I managed to solve it. I looped through all my canvases using toDataURL() JS function and then sending them via AJAX. I acomplished it firstly sending the image data in PNG format in my JS:

    $("canvas").each(function() {
       var dataURL = ($(this)[0]).toDataURL("image/png");
    
       if(dataURL.indexOf("AAAAAAAA") == -1){
         var filename = $(this).parent().closest('.grafico').attr('id') + ".png";
         $.ajax({
            url: "guardar_graficos.php",
               data: {
                   image: dataURL,
                   filename: filename
                   },
                   type: "POST",
                   dataType: "image/png"
                }); 
              }
          });
    

    And then catching and saving it in the server side using PHP:

    $upload_dir = "foo/";
    $iid = $_POST['image'];
    $filename = $_POST['filename'];
    $img_encode = str_replace('data:image/png;base64,', '', $iid);
    $img = str_replace(' ', '+', $img_encode);
    $data = base64_decode($img);
    $file = $upload_dir.$filename;
    unlink($upload_dir.$filename);
    file_put_contents($file, $data);