Use AJAX to display php generated image - php

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?

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

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.

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.

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 + '">')
}
})
})
})

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

Related

Using AJAX / jQuery to refresh an image

This is probably a simple question but I am stumped and just don't know where to start.
I have a PHP script (image_feed.php) that returns a URL to an image. Every time this URl is called it returns the latest image available (the image changes every couple of seconds).
What I want to happen is that when the page loads, there is an AJAX call to image_feed.php, which returns the latest url. This URl is then inserted into the HTMl replacing the appropriate image src.
After 5 seconds, I want the process to repeat, and for the image to update. However, I don't want the image to be swapped until it has finished loading, and I want to avoid a white space appearing before the new image loads.
At the moment I have the following jQuery, which simply loads the return value of image_feed.php directly into a div called #image1. image_feed.php is correctly formatted to provide a html image tag.
$(document).ready(function(){
var $container = $("#image1");
$container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>')
var refreshId = setInterval(function()
{
$container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>');
}, 5000);
});
This works, but there is a problem. I get a white space the size of the image in IE and Firefox every time the image refreshes, because the image takes a while to download.
I know what I need to is for image_feed.php to return the plain URL to the image. I then use some jQuery to request this URL, pre-load it and then swap it with the existing image.
However, I'm still struggling to get anywhere. Could someone be so kind as to give me some pointers / help?
$(document).ready(function() {
var $img = $('#image1');
setInterval(function() {
$.get('image_feed.php?CAMERA_URI=<?=$camera_uri;?>', function(data) {
var $loader = $(document.createElement('img'));
$loader.one('load', function() {
$img.attr('src', $loader.attr('src'));
});
$loader.attr('src', data);
if($loader.complete) {
$loader.trigger('load');
}
});
}, 5000);
});
Untested. Code above should load the new image in the background and then set the src attribute of the old image on load.
The event handler for load will be executed only once. The .complete check is necessary for browsers that may have cached the image to be loaded. In such cases, these browsers may or may not trigger the load event.
You can. When you want to reload something, you can just append a search query, so that it refreshes the source.
For Eg., when there is a frequently changing image (say captcha) and you wanna load it again, without refreshing the browser, you can do this way:
Initial Code:
<img src="captcha.png" alt="captcha" />
Refreshed Code:
<img src="captcha.png?1" alt="captcha" />
The script used here would be just:
var d = new Date();
$('img').attr('src', $('img').attr('src') + '?_=' + d.getMilliseconds());
Hope this helps! :)
Consider, if you have to fetch the URL again from the server, for a new image URL, you can do this way:
$.ajax({
url: 'getnewimageurl.php',
success: function(data) {
$('img').attr('src', data);
}
});
The server should return only a new image name in it. For eg., the PHP code should be this way:
<?php
$images = array("jifhdfg", "jklduou", "yuerkgh", "uirthjk", "xcjhrii");
die($images[date('u') % count($images)] . ".png"); // Get the random milliseconds mod by length of images.
?>
I suggest you use jQuery 'onImagesLoad' Plugin
This provides you with a callback when an image has finished loading.
When you receive new image URL from server, you create a new <img object with src="new_url_from_server" and attach 'onImagesLoad' callback to it. When your callback is called, your image has finished downloading.
Now you can just replace the 'src' attribute of old img object with new_url_from_server.
Since new image is already avaiable in cache, it will not be downloaded again and will be immediately displayed!
Aletrnatively, you can hide the old image and add this new image to DOM (not required if above works correctly)
Some bare bones sample could be like this:
<!DOCTYPE html>
<html>
<body>
<img id='bla' src="10.jpg" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.onImagesLoad.js"></script>
<script type="text/javascript">
$(function(){
var img = $('<div><img src="http://myserverbla/images/verybig.jpg"></img></div>');
img.onImagesLoad({
all : allImgsLoaded
});
function allImgsLoaded($selector){
var allLoaded = ""; //build a string of all items within the selector
$selector.each(function(){
$('#bla').attr('src','http://myserverbla/images/verybig.jpg');
})
}
});
</script>
</body>
</html>

How to set HTTP header img-type jpeg/png in AJAX when updating captcha?

Use jquery + php. Doing custom AJAX captcha. i.e user clicks on image, it automatically updates.
<script src="/js/jquery.js"></script>
<script>
$(document).ready(function(){
$.post('/captcha.php', {}, function(resp){
$("div").html(resp);
});
});
</script>
<div></div>
in PHP header already sent, so if it includes into <img src="/captcha.php" /> it prints captcha in jpeg. The problem seem to be is header that need to be sent. So, how can i do this? The header is sent in PHP. It doesnt work in js.
If you want to change an image in an HTML document, then change the src attribute of the image (or replace the image element with a new one). Don't use XMLHttpRequest at all.
Add header function in Your captcha.php file:
header('Content-Type: image/jpeg');
If you are loading the source from a different script then you can simply send the src of the file through a string value. In that way your captcha.php code becomes something like this
$source="/path/to/the/file.jpg";
header("Content-type:text/plain");
print $source;
When you receive it you can do the following to change the source
$("#changeCaptchaButton").click(function() {
$.ajax({
url: "captcha.php",
cache: false,
success: function(data) {
alert("changing source of image");
var source=data;
$("#captchaImg").attr("src", source);
}
});
});
If you are doing the change in the current script then don't use the ajax but use the latter jQuery method

Get the Width of Div and LIMIT the mySQL query according to no of elements?

I needed to display number of images in
<li><img class='1'><img class='1'><img class='1'></li>
<li><img class='1'><img class='1'><img class='1'></li>
but as my div is auto increasing according to screen width. I needed to calculate number of images to display according to the width of div , suppose width is 1200px and each image will be of 150px . so the number of image to display are 8 .
<script type='text/javascript'>
var screen_width = document.getElementById('div_1').offsetWidth();
var no_of_images =Math.round(screen_width/100);
</script>
I am getting the images from mysql database, using LIMIT query .. I want to LIMIT it to no of images i got using var no_of_images. But as their is no direct rule of integrating javascript variable into mysql query. i want to pass it to PHP variable and then use it in Mysql. But unfortunately i dont know how to do it.
You can use the document.ready event handler to make sure the DOM is ready to be manipulated and then make an AJAX request to your server-side script that could output the HTML for the correct number of images to place in the container:
//wait for the `document.ready` event to fire
$(function () {
//cache the container element since it will be used later more than once
//also get the width of the container and figure out how many 150px wide images can fit without being clipped
//note that this does not take into consideration any padding/margin/border for the images
var $container = $('#div_1'),
screen_width = $container.width(),
no_of_images = Math.floor(screen_width / 150);
//create an AJAX call to your server-side script to get the image HTML
$.ajax({
url : '<URL>',
type : 'get',//or 'post'
data : { 'no_of_images' : no_of_images },//jQuery will handle data encoding if you pass it an object
success : function (serverResponse) {
//now the AJAX request has returned successfully so this fades the container out, replaces it's HTML with the server response and then fades back in
$container.fadeOut(500, function () {
$container.html(serverResponse).fadeIn(500);
});
},
//if an error occurs with the AJAX call this is how you handle it, you may just try to re-send the AJAX call
error : function () {
alert('an error occured');
}
});
});
you can pass it as a get param when loading the page. e.g. when creating the link to load the next page just add it as param. on initial page load you get all the images bu display only the ones you need for the available resolution
You have to use AJAX.
<script type='text/javascript'>
var screen_width = document.getElementById('div_1').offsetWidth();
var no_of_images =Math.round(width/100);
$.ajax({
type: "post",
url: "script.php",
data: "no_of_images="+no_of_images,
success: function(){
// do something
}
});
</script>
You have to use jQuery to get my code working, cause i used the jQuery method $.ajax().

hold off showing image until fully loaded in html result via ajax

I know a lot of questions have been asked about this question but i am still not abale to get my head round it.
I have a number of images that when clicked, i get the big image via ajax. The result from ajax a load of html that goes into my chosen div. the reason for this is that i plan on using other information on the page that ajax returns.
The html that gets returned contains the img tag and i am wanting hold off showing the image until it is fully loaded.
here is what i have so far:
function getimage(sent_data){
$("#gallery").hide()
$.ajax({
type: "GET",
url: "gallery/name.php?",
data: "id=" + sent_data,
success: callback
});
}
function callback(data, status){
$("#gallery").html('').hide(); // you need to remove the old image
$("#gallery").removeClass("loading").html(data).fadeIn("slow");
}
and the data returned is:
<a href="test.jpg" class = "cloud-zoom" rel="position: 'inside' , showTitle: false, adjustX:-4, adjustY:-4">
<img src="test.jpg" width="450" height="301" alt="johnboy"/></a>
Thank you.
I haven't tried it but this should work.
when you get your html data from your server place the returned html but not show, then add load handler to your gallery element and when it loads show your html.
$("#gallery").load(function(e) {
$(this).show();
});
function callback(data, status){
//edit: you must place your returned data
$("#gallery").html(data).hide(); // you need to remove the old image
}

jQuery load raw image from .php file, how to include

I have a page with some pictures drawn in php. I load a file with the reference-ids. Then the page is done loading, each of the image-elements will be loaded using ajax. (for example ajax_image.php?url=http://www.opti.com/1). Ajax_image then draws a image and outputs it using header jpeg.
The problem is that when I try to "include" or show this picture in my reference-file the output is not a picture, it's text saying:
�JPEG
My jQuery looks like this:
$.ajax({
url: "ajax_picture.php?url="+escape($('#bilde1').attr('rel')),
cache: false,
success: function(html){
$('#bilde1').html(html);
alert('Picture 1 loaded');
sizeChangeCallback();
}
});
I assume I get this problem because I use html to include the picture in the reference-file. But I have no idea what function to use, in order for it to understand that it's a raw picturefile.
You don't need to use ajax for this. Instead, simply output an <img> tag like this:
var imgTag = '<img src="ajax_picture.php?url=' + escape($('#bilde1').attr('rel')) + '" />';
$('#bilde1').html(imgTag);

Categories