I have a php script that randomly generates an image. Something like this:
Instead of $('#image').html('<img src="' + data + '">')
, try $('#image').attr('src', data);
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) );
});
});
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()));
});
The resulting image has to be base64 encoded to be included like that.
So you need to do the following:
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 + '">')
}
})
})
})
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.