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?

3
  • Try with expiring browser cache Commented Apr 4, 2012 at 7:30
  • @ShaktiSingh Thank you for your response. I expired it, no success. Commented Apr 4, 2012 at 7: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. Commented Apr 4, 2012 at 7:35

6 Answers 6

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()));
});
Sign up to request clarification or add additional context in comments.

Comments

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) );
      });
 });

4 Comments

Thank you for your response. This does not seem to work for me.
@AnPel I fixed my answer. The browser probably thought it wouldn't need to load the image again, since the URL hasn't changed.
You fixed it how? The image will still be taken from the cache. EDIT: You fixed it now :-)
@devnull69 By adding a random GET parameter to the request. Prolly better if you would add Unix-time to it though...
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.

1 Comment

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.
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.

2 Comments

you mean I replace [BASE64] with the ajax string response?
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.
-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 + '">')
            }
        })
    })
})

1 Comment

This won't work. The PHP files sends raw image data and not an image URL
-1

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

3 Comments

This won't work, the PHP file sends raw image data and not a URL
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.
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 :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.