Using AJAX / jQuery to refresh an image - php

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>

Related

Using AJAX to generate behind the scenes?

I want to create images using imagejpeg() but they seem to take longer to render than the time it takes to load the page, therefore the images are either not displaying or they are truncated.
I have tried to delay the loading of the page until the images are completely created without resolve so now I am attempting to get the images created prior to page load.
My fail is as follows:
function createimages(x) {
$.post("image-dev.php?curID=" + x, function(rdata) {
console.log(rdata);
});
setTimeout(function() {
window.location = "image-review.php?curID=" + x;
}, 5000);
}
image-dev.php is my image creation file that pulls all necessary data from my DB then uses imagejpeg to create and save my folder.
If I navigate directly to image-dev.php with the proper ID associated. My images are created and saved properly.
My hopes were that I could use AJAX to call image-dev.php sometime before loading the image review page. I hoped that this would 'pre-develop' the images so that they would load properly when reviewed.
My console.log of the rdata shows that the image-dev.php is loading and executing, but the files aren't being created.
Is there an issue with creating images behind the scene?
When image is already created php can return "true".
With ajax you can do that.
function createimages(x){
$.ajax({
url: "image-dev.php?curID="+x,
beforeSend: function( xhr ) {
//here you can hide elements or other DOM manipulations
}
}).done(function( rdata) {
console.log(rdata);
//when php is ready you can show images or other DOM manipulations
}
});
});
kristiyan, Thanks!
I have decided to give up on the idea of predeveloping my images and used your tactic.
Since the images were still truncating when displayed, I now have placeholder images on the image review page and am loading the new images in after they complete.
I'm not yet sure how to see if an image is truncated, so I had to add in a delay before resetting the placeholders src attribute.
$.ajax({
type: 'POST',
url: "image-dev.php?curID="+x,
success: function(rdata) {
console.log(rdata);
setTimeout(function(){
$('#placeholder').attr('src', 'newImage.jpg');
},5000);
}
});
This seems to be working acceptably!

Reload random div content every x seconds

I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.

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

Want to show “loading” image during the image download - Javascript

I am using the following script to display big images on mouse over the small images (example photo attached in the last). I want to show the 'loading' image (like this) while the big image is being downloaded from the server. How can this be achieved?
Note: I have asked a similar question here but I was not successful in applying the append function to the following code. Please help.
<script type="text/javascript">
function showIt(imgsrc)
{
var holder = document.getElementById('imageshow');
var newpic= new Image();
newpic.src=imgsrc;
holder.src=imgsrc;
holder.width = newpic.width;
holder.height=newpic.height;
}
</script>
<body>
/***on hover, xyz.jpg will be replaced by bigA.jpg and so on***/
<img src="smallA.jpg" onMouseOver="showIt('bigA.jpg')"/>
<img src="smallB.jpg" onMouseOver="showIt('bigB.jpg')"/>
<img src="xyz.jpg" id="imageshow" />
</body>
Images have a load event. As long as you set the load handler before the image.src is set, you should get notified when the image has successfully loaded or encounters some kind of error in loading. I do that very thing in a slideshow that I wrote so I know when the next image is ready for display and I display a wait cursor (animated gif like you're wanting) if the image has been delayed more than one second beyond it's appointed display time so the user knows what's going on.
In general, you can do something like this:
function loadImage(url, successHandler, errorHandler) {
var myImg = new Image();
myImg.onload = myLoadHandler; // universally supported
myImg.onabort = myErrorHandler; // only supported in some browsers, but no harm in listening for it
myImg.onerror = myErrorHandler;
myImg.src = url;
function myLoadHandler() {
successHandler(myImg, url);
}
function myErrorHandler() {
if (errorHandler) {
errorHandler(url);
}
}
}
Using code like this, you can display the wait cursor when you initiate the image load and hide it when the successHandler gets called.
If there were any other listeners to these events, then you should use addEventListener or attachEvent instead of onload, onabort, onerror, but if there's only one listener, you can go either way.
If the desired images are known in advance, then it's sometimes a better user experience (less waiting) to preload images that may be used later. This gets them into the browser's memory cache so they will appear instantly when needed. One can preload images either in HTML or in JS. In HTML, just insert tags into the web page for all the desired images (but hide them with CSS). In JS, just create an image array and create the image objects:
// image URLs to preload
var preloadImageURLs = [
"http://photos.smugmug.com/935492456_5tur7-M.jpg",
"http://photos.smugmug.com/835492456_968nf-M.jpg",
"http://photos.smugmug.com/735492456_3kg86-M.jpg",
];
var preloads = []; // storage for preloaded images
function preloadImages() {
var img, i;
for (i = 0; i < preloadImageURLs.length; i++) {
img = new Image();
img.src = preloadImageURLs[i];
preloads.push(img);
}
}
This will cause all the images in the preloadImageURLs array to be preloaded and available instantly later on in the life of the web page, thus preventing any user delays while waiting for images to be loaded. Obviously, there's a short amount of time for the preloaded images to actually get loaded, but for smallish images that usually happens before the user interacts with the web page so it makes for a faster feel to dynamic parts of the web page that use images.
<img id=access src=loading.gif>
<script>
window.onload=function(){
document.getElementById('access').src='access.jpg';
}
</script>
Hope this helps.

Load more function in Javascript

EDIT: This question was initially too general, I think. So What I really need is a very good tutorial on how to implement the Load More function on Safari for iPhone just like the Twitter website(mobile.twitter.com) does. Just a wordpress plugin won't really help. But if the plugin is well explained, like if it is wptouch, home(that also has this function) that can also do.
I know that it doesn't really matter that it is being displayed on a mobile device, but the point I am stressing is that if such a function is well explained, then it will be up to me to know how to customize it to suit me.
I am using a javascript function to load entries that come from the database dynamically, so that content opens in the same page (like with twitter(tweets feed) and facebook(news feed)).
The php/html version(That opens a page in a new tab) is
echo 'Load more entries› ';
The javascript/ajax version:
<div id="call_hv<?php echo md5($_SERVER['REQUEST_URI']); ?>" class="ajax-load-more">
<img id="spinner<?php echo md5($_SERVER['REQUEST_URI']); ?>" class="spin" src="<?php bloginfo('template_directory'); ?>/images/main-ajax-loader.gif" style="display:none" alt="" />
<a class="ajax" href="javascript:$ajax_hv('#spinner<?php echo md5($_SERVER['REQUEST_URI']); ?>').fadeIn(200);
$ajax_hv('#ajaxentries_hv<?php echo md5($_SERVER['REQUEST_URI']); ?>').load('form='<? echo $form_id; ?>&page=<?php echo $page+1;?>', {},
function(){ $ajax_hv('#call_hv<?php echo md5($_SERVER['REQUEST_URI']); ?>').fadeOut();})">Load more entries...
</a>
The basic idea is to listen to scroll events, and implement paging on the server side.
A scroll event is fired whenever the document or a contained HTML element scrolls. I'll use this sketch for reference keeping the following things in mind:
Let's say the height of the browser window is 800px, and the initial height of the content is 2500px. The threshold for loading AJAX content is when the user scrolls to the bottom 100px of our content (after the first 2400px).
We will need to keep track of the following 2 items:
Items/Pages loaded so far.
How far are we from the bottom of
the page.
The code references are in MooTools, but the concept is the same. Converting it to jQuery is a trivial task once you understand it.
var maxPage = 1;
var threshold = 100;
We need to know whenever the page scrolls, so add a handler for scroll events. Find the scroll distance to the bottom of the page. If it's less than the defined threshold (100px), then fire off an AJAX request loading the next page. When the response comes (if successful), append it to the page and increment maxPage number.
Another thing to keep in mind is to only fire an AJAX request if content is not already being loaded. Have a flag that indicates whether the page request is still pending.
var isLoading = false;
window.addEvent('scroll', function() {
// the height of the entire content (including overflow)
var contentHeight = window.getScrollSize().y;
// current scroll is height of content that's above the viewport plus
// height of the viewport.
var contentScrolled = window.getScroll().y + window.getSize().y;
var distanceToBottom = contentHeight - contentScrolled;
var closeToBottomOfPage = distanceToBottom < threshold;
var shouldLoadMoreContent = !isLoading && closeToBottomOfPage;
if(shouldLoadMoreContent) {
// create an ajax request
var request = new Request({
url: 'http://www.example.com/more',
onSuccess: function(responseText) {
$('page').append(responseText);
maxPage++;
},
onRequest: function() {
isLoading = true;
},
onComplete: function() {
isLoading = false;
}
});
// fire off ajax request with the page # as a querystring param
request.send({page: maxPage});
}
}
Commonly called an Infinite scroll. There are plugins for jQuery and Wordpress:
http://www.infinite-scroll.com/

Categories