Google graphic image/ asynchronous request

Asked

Viewed 9 times

0

I am mounting a report where I need to generate graphics through the google Chart api and generate the graphic image to insert into the report pdf.

I can generate the graphic and I can generate the image but I can only upload the image after the execution of my php code that mounts the pdf, with this in the PDF montage is performed the image search in the directory but it does not exist yet because it is only generated at the end of page loading. Below are excerpts of code from the PDF montage, graphic montage and graphic image upload.

What is happening is that my AJAX call to save the graphic image is taking place after the PDF assembly, as I can make it run before the php code that searches the image and generates the pdf?

PDF Assembly (PHP):

. . .

<?php
$ChartPie = new skChartGooglePizza($title, $data, '', $grafW, $grafH, false);
print_rpre($ChartPie->chartGoogle(true, KM::getDirPublicClientTmp(), $nmArquivo));
$pdf->Image(KM::getDirPublicClientTmp().$nmArquivo.'.png', $pdf->PageCenter() - $grafW * $rasao_pdf / 2, $pdf->GetY(), $grafW * $rasao_pdf, $grafH * $rasao_pdf, 'png');
$pdf->SetY($pdf->GetY() + $grafH * $rasao_pdf);
$pdf->Ln(8);
$pdf->SetLineWidth(1);
$pdf->Line($pdf->GetX(), $pdf->GetY(), $pdf->PageRight(), $pdf->GetY());
$pdf->SetLineWidth(0);
$pdf->Ln(8);
$pdf->Output();
?>

Google Graphic Montage(JS):

. . .

class skChartGooglePizza extends skChartGoogle {

/**
 * Coluna que exibe o valor do campo de acordo com o tipo do banco de dados, como em {@see skDbGrid}
 * @param string $sCaption
 * @param string $sName
 * @param integer $boxWidth
 * @param integer $boxHeight
 */
public function __construct($title, $aData, $param='', $boxWidth = 0, $boxHeight = 0, $imprimirChart = true) {
    $this->title            = $title;
    $this->param            = $param;
    $this->aData            = $this->formatarDados($aData);
    $this->defaultBoxWidth  = $this->boxWidth($boxWidth);
    $this->defaultBoxHeight = $this->boxHeight($boxHeight);
    
    /**
     * Gera o gráfico (dashboard)
     */
    if ($imprimirChart) {
        $this->chartGoogle();
    }

}

public function chartGoogle($ChartToImage = false, $PathImage = '', $nmArquivo = '') {
    
    $chart  = '';
    $chart .= '<script type="text/javascript" src="https://www.google.com/jsapi"></script>' . PHP_EOL;
    $chart .= '<script type="text/javascript">' . PHP_EOL;
    $chart .= '     google.charts.load("visualization", "1", {packages:["corechart"]});' . PHP_EOL;
    $chart .= '     google.charts.setOnLoadCallback(drawChart);' . PHP_EOL;
    $chart .= '     function drawChart() {' . PHP_EOL;
    
    /**
     * Dados que serão apresentados no gráfico
     */
    $chart .= '         var data = google.visualization.arrayToDataTable(' . PHP_EOL;
    $chart .=               $this->aData;
    $chart .= '         );' . PHP_EOL;
    
    /**
     * Titulo do gráfico (dashboard)
     */
    $chart .= '         var options = {' . PHP_EOL;
    $chart .= '             title: " ' . ucwords($this->title) .  ' "' . PHP_EOL;
    $chart .= '         };' . PHP_EOL;
    
    $chart .= '         var chart_google = document.getElementById("chart-google");' . PHP_EOL;
    $chart .= '         var chart_google_image = document.getElementById("chart-google-image");' . PHP_EOL;
    $chart .= '         var chart = new google.visualization.PieChart(document.getElementById("chart-google"));' . PHP_EOL;

    /*
    *Retornar imagem do gráfico 
    */
    if ($ChartToImage && $PathImage) {
        $chart .= '         google.visualization.events.addListener(chart, "ready", function () {' . PHP_EOL;
        $chart .= "                 chart_google.innerHTML = '<img id=\"chart-image\" src=\"'+chart.getImageURI()+'\">'". PHP_EOL;
        $chart .= '                 save_chart_image(chart.getImageURI(), "'.$PathImage.'", "'.$nmArquivo.'");'. PHP_EOL;
        $chart .= '         });'. PHP_EOL;
        
        // $chart .= '          chart_google.ready(function (){';
        // $chart .= '                  save_chart_image(chart.getImageURI(), "'.$PathImage.'", "'.$nmArquivo.'");'. PHP_EOL;
        // $chart .= '          });'. PHP_EOL;
        
        $chart .= '         function save_chart_image(chart_image, chart_image_path, chart_image_file_name) {'   . PHP_EOL;
        $chart .= '             $.ajax({' . PHP_EOL;
        $chart .= '                 url       : "'.KM::getWebApp().'../runtime/skin.wform/upload_image_chart.php",' . PHP_EOL;
        $chart .= '                 type      : "post",' . PHP_EOL;
        $chart .= '                 dataType  : "json",' . PHP_EOL;
        $chart .= '                 data      : {"chart_image":chart_image, "chart_image_path":chart_image_path, "chart_image_file_name":chart_image_file_name, "type_file":"png"},' . PHP_EOL;
        $chart .= '                 async     : true,' . PHP_EOL;
        $chart .= '                 beforeSend: function() {' . PHP_EOL;
        // $chart .= '                      window.location.reload();' . PHP_EOL;
        $chart .= '                 },' . PHP_EOL;
        $chart .= '                 success   : function(answer) { ' . PHP_EOL;
        $chart .= '                     console.log(answer);' . PHP_EOL;
        $chart .= '                 },' . PHP_EOL;
        $chart .= '                 error     : function(xhr, ajaxOptions, thrownError) {' . PHP_EOL;
        $chart .= '                     console.log(xhr.status);' . PHP_EOL;
        $chart .= '                     console.log(ajaxOptions);' . PHP_EOL;
        $chart .= '                     console.log(thrownError);' . PHP_EOL;
        $chart .= '                 }' . PHP_EOL;
        $chart .= '             });';
        $chart .= '         }'. PHP_EOL;
    }
    
    $chart .= '         chart.draw(data, options);'. PHP_EOL;
    $chart .= '     }' . PHP_EOL;
    $chart .= '</script>' . PHP_EOL;
    
    /* recebe os parametros de pesquisa */
    $chart .= $this->param;
    
    /**
     * Box onde será apresentado o gráfico (dashboard)
     */
    if (!empty($this->param)) {
        $chart .= '<input type="button" id="btn-chart-abrir" value="Editar parâmetros de pesquisa" />' . PHP_EOL;
        $chart .= '<div id="chart-google" style="width:98%;margin:0 1%;height:85%;"></div>' . PHP_EOL;
    } else {
        // $chart .= $ChartToImage ? '<form id="chart_form" action="'.KM::getWebApp().'../runtime/skin.wform/upload_image_chart.php" method="POST" accept-charset=utf-8 >'. PHP_EOL : '';
        $chart .= '<div id="chart-google" style="width:98%;margin:53px 1% 0 1%;height:85%;"></div>' . PHP_EOL;
        // $chart .=  $ChartToImage ? '</form>' . PHP_EOL : '';
    }
    
    if ($ChartToImage) {
        // return $chart;;
        return $chart;
    }else {
        print $chart;
    }
    
}

}

File called via AJAX that uploads the graphic image (PHP):

<?php

/**
 * Realiza upload do gráfico em imagem para o caminho passado
 */

if(isset($_POST['chart_image'], $_POST['chart_image_path'], $_POST['chart_image_file_name'], $_POST['type_file'])){
    $data = $_POST['chart_image'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);
    $nmArquivo = $_POST['chart_image_path'] . $_POST['chart_image_file_name'] . '.' . $_POST['type_file'];
    if(file_put_contents($nmArquivo, $data)){
        chmod($nmArquivo, 0777);
        $ret['tmp_dir']= $_POST['chart_image_path'];
        $ret['tmp_name']= $_POST['chart_image_file_name'];
        $ret['type']= $_POST['type_file'];
        $ret['size']= filesize($nmArquivo);
        echo json_encode($ret);
    }
}
?>
  • If I can return the Base64 code of the generated image to php that mounts the pdf would also serve me pq then I can save the image before the pdf is generated but also I can not make this return.

  • IGNORE THE COMMENTS LEFT (//)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.