0

I have a PHP script that computes the next value in a time series data and plots that to a graph as a PNG image. I will provide this data through AJAX, and PHP creates the PNG image. Now, how do I get the generated PNG image from PHP as an AJAX response? The code is as follows:

PHP:

<?php

$data = json_decode($_POST['data']);
// Some code to calculate the next value in this series
plotRenderRegression( $polynomialRegression, $coefficients, 0, 11 , $colorMap[ "Blue" ] ); 

header( "Content-Type: image/png" ); 
echo imagePNG( $image ); 
?>

JS:

$.post({
    dataType: "image/png",
    url: "predict.php",
    data: {
        sent: true,
        data: "[[1,0.63151965],[2,0.58534249],[3,0.43877649],[4,0.2497794],[5,0.07730788],[6,0.08980716],[7,0.11196788],[8,0.19979455],[9,0.4833865],[10,0.9923332]]"
    },
    success: function (img) {
        console.log(img)
        i = new Image();
        i.src = img;
        console.log(img);
        $("#imgdiv").prepend(i);
    },
    error: function (error, txtStatus) {
        console.log(txtStatus);
        console.log('error');
    }
});

Console Output:

�PNG


IHDRX�Ao�NPLTE������00�������000������������333MMMfff���������������vD���IDATx��][��*�*>���o���$ ?$[��ɑq� Ι�����������2������Fp�;D33������c���وeĪF�iO̮H�����r*3'���[N
o~p#���X��ˀ���ub��T�X�,���׽���q�.�R��}� �]��#æy����l}�
}:U���,�����'�w�W_�0S9ԡ�wl�0�עOfTc8qw��9,=�s����7��^��h�U�1b-��?��鎿G����Ag��}����7Gg��GY���R��4y�   LE����8'o�  �+L>A��ʻ�e�hry��سد�끷�j����`#�����)ժϜΟc-)_ck���  ���=2�W�rY�X�gY]���1�H�T�3�*�]'�V�T̼t$���ྑN��&�K���%qp�cuf���2}8����`�PA'VF%6�PoC-6!���ky����8䪏U�:������,�Ƌ�
�9Uby���W�
���共�  .....

What am I doing wrong here ?

UPDATE 1:

I've changed the JS code as follows, but it still get a broken image

success: function (data) {
    $('#imgdiv').html('<img src="data:image/png;base64, ' + btoa(unescape(encodeURIComponent(data))) + '" />');
} 
Aditya Vikas Devarapalli
  • 3,186
  • 2
  • 36
  • 54

1 Answers1

0

You can't set SRC to the image itself. You can solve the problem in two ways:

1- Create a temporary file and return a link to it in your PHP file

2- base64 encode the PNG and pass it to src the way you're currently doing.

On both those ways, you'd probably have to lose the "dataType" filter of jQuery for the response to be interpreted as successful.

Example of final HTML (src set via your JavaScript Ajax):

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby // blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC />"

<img src="data:image/png;base64,[base64_encoded_png_goes_here] />"

henry700
  • 179
  • 3
  • 8