Use AJAX to display php generated image

Go To StackoverFlow.com

1

I have a php script that randomly generates an image. Something like this:

<?php
$image = imagecreatetruecolor(400,200);

// process image

// rendering image
header("Content-type: image/jpeg");
imagejpeg($image);
?>

My html looks like this:

<img id="image" src="/models/plugins/image.php"/>
<button id="button">Get new image</button></body>

Then I have a jquery file that handles the click to the button, so that a new random image is loaded when the button is clicked:

$(function(){
    $('#button').click(function(){
        $.ajax({
            url: 'models/plugins/image.php',
            success: function(data){
                $('#image').html('<img src="' + data + '">')
            }
        })
    })
})

I use firebug, I can see that request is actually sent and that the response is received successfully, but the image does not change.

What am I doing wrong and how can I fix this?

2012-04-04 07:28
by ppp
Try with expiring browser cach - Shakti Singh 2012-04-04 07:30
@ShaktiSingh Thank you for your response. I expired it, no success - ppp 2012-04-04 07:31
You would have to use data returned in the Data URI scheme to do this. Your PHP doesn't look like you are doing this - m90 2012-04-04 07:35


7

I added another answer because I think that none of the previous answers solved the problem. I think, the only thing the OP wanted was to update(!) the image when the button is clicked. So there is no need for an Ajax request, just reload the image. And you can enforce that by appending a random query string to the image's src attribute.

$('#button').click(function() {
    var $image = $('#image');
    var plainSrc = $image.attr('src').split("?")[0];  // disregard previous query string
    $image.attr('src', plainSrc + "?" + (new Date().getTime()));
});
2012-04-04 07:45
by devnull69
You win. This did it - ppp 2012-04-04 07:52
Good show (Y)! - mim 2012-04-04 07:56
thank you devnull69! you made my day - Luca 2014-09-01 07:49


4

The src attribute of an image tag actually expects an URL not actual JPEG data.

Try this:

 $(function(){
      $('#button').click(function(){
          $('#image').attr('src', 'models/plugins/image.php?rand=' + Math.floor(Math.random()*1000) );
      });
 });
2012-04-04 07:32
by Khôi
Thank you for your response. This does not seem to work for me - ppp 2012-04-04 07:38
@AnPel I fixed my answer. The browser probably thought it wouldn't need to load the image again, since the URL hasn't changed - Khôi 2012-04-04 07:50
You fixed it how? The image will still be taken from the cache. EDIT: You fixed it now :- - devnull69 2012-04-04 07:51
@devnull69 By adding a random GET parameter to the request. Prolly better if you would add Unix-time to it though.. - Khôi 2012-04-04 07:54


1

To use the image inside the src attribute you need to provide a valid URI, for example a data-URI:

<?php
$image = imagecreatetruecolor(400,200);

// process image

// create image URI
ob_start();
imagejpeg($image);
echo "data:image/jpeg;base64,", base64_encode(ob_get_clean());
?>

I once compiled a more detailed answer for a similar question.

2012-04-04 07:35
by hakre
I don't think this actually works like that, since imagejpeg() returns only true-false value when used without a location, it does not return a string according to documentation. It would have to be written to output buffer and read from buffer, unless storing the image in filesystem - kingmaple 2012-04-04 07:40
My bad, you're right. Fixed the example - hakre 2012-04-04 07:42


0

The resulting image has to be base64 encoded to be included like that.

So you need to do the following:

  • Edit the image
  • Get resulting image in data string.
  • To get image string, you either store it to filesystem and read it through file_get_contents() (useful for cache) or use imagejpeg() without location, which places the image in output buffer. To get the value from output buffer use ob_start() and ob_get_contents().
  • Convert data string of the image to base64 (using base64_encode())
  • Return this string to browser
  • Set image "src" field to "data:image/png;base64,[BASE64]" where [BASE64] is the string returned from PHP.
2012-04-04 07:35
by kingmaple
you mean I replace [BASE64] with the ajax string response - ppp 2012-04-04 07:48
Both are valid options. You can either echo everything the way hakre posted, so PHP returns everything (data:image/png;base64,[BASE64]) and you place it as src="", or you can build that string in JavaScript itself. It depends what you need (it's 'better' not to have PHP echo the "data:image/png;base64," part in case that picture generation is used elsewhere as well - kingmaple 2012-04-04 12:04


-1

The image you are calling is being cached by browser, use a query string at the end of your image url to let the browser thing its a new image and it should not use cached version.

Something like this:

$(function(){
    $('#button').click(function(){
        $.ajax({
            url: 'models/plugins/image.php?t='+((new Date).getTime()),
            success: function(data){
                $('#image').html('<img src="' + data + '">')
            }
        })
    })
})
2012-04-04 07:35
by mim
This won't work. The PHP files sends raw image data and not an image UR - devnull69 2012-04-04 07:49


-1

Instead of $('#image').html('<img src="' + data + '">'), try $('#image').attr('src', data);

2012-04-04 07:37
by Tuan
This won't work, the PHP file sends raw image data and not a UR - devnull69 2012-04-04 07:50
Yeah, well in the question, he used data as a string, so I had to assume that it was, in fact, a string. Consider downvoting the question instead - Tuan 2012-04-04 07:56
I see your point, but I won't downvote the question. Because if the OP knew this he wouldn't have asked in the first place :- - devnull69 2012-04-04 07:58
Ads