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?

ppp
  • 2,035
  • 9
  • 32
  • 52

6 Answers6

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()));
});
devnull69
  • 16,402
  • 8
  • 50
  • 61
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) );
      });
 });
Khôi
  • 2,133
  • 11
  • 10
  • Thank you for your response. This does not seem to work for me. – ppp Apr 04 '12 at 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 Apr 04 '12 at 07:50
  • You fixed it how? The image will still be taken from the cache. EDIT: You fixed it now :-) – devnull69 Apr 04 '12 at 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 Apr 04 '12 at 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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • 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 Apr 04 '12 at 07:40
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.
kingmaple
  • 4,200
  • 5
  • 32
  • 44
  • you mean I replace [BASE64] with the ajax string response? – ppp Apr 04 '12 at 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 Apr 04 '12 at 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 + '">')
            }
        })
    })
})
mim
  • 477
  • 1
  • 3
  • 13
-1

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

Tuan
  • 5,382
  • 1
  • 22
  • 17
  • This won't work, the PHP file sends raw image data and not a URL – devnull69 Apr 04 '12 at 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 Apr 04 '12 at 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 Apr 04 '12 at 07:58