please help to resolve the following issues:
There is a page which loads the image.
50 pictures.
How to make, that images would be displayed gradually (example google photo)?
$(document).ready(function(){
$.ajax({
type: 'POST',
url: document.location.href,
dataType: 'html',
data: {'ajax-query': 'true'}
success: function(data){
$('#divgallery').append(data);
}
});
})
Here comes the server code
if($i=0; $i<50;$i++){ echo '<img src="/img/' . $img . '">'; }
They are displayed all at once, after the server-side code is done.
How display images on each iteration?
Any tips, link or code example would be useful.
Firstly, on the server site return the image links in such way that they can be retrieved individually. I recommend JSON fromat.
$res = array();
if($i=0; $i<50;$i++){ $res[] = '<img src="/img/' . $img . '">'; }
echo json_encode($res);
Secondly, after you get the data you have to add the images one by one, but with a delay between the additions.
success: function(data){
delayAppend($("#divgallery"), data, 0);
}
And the delayAppend function would be something like:
function delayAppend($div, data, index){
if(index >= data.length)
return;
$div.append(data[index]);
setTimeout(function(){ delayAppend($div, data, index+1); }, 500);
}
Here is a demo of the delayAppend function: http://jsfiddle.net/s7Q8W/
Note: Code not fully tested.
Related
This is kind of a difficult question to pose as I don't have a lot of backend knowledge so forgive me if my jargon is not up to par.
Basically, I have a gallery of images and I need users to be able to "like" an image and have that increment a counter which then is stored to the server. So, if say 50 users liked a particular image, it would show "50" on that image to all users.
I'm assuming php and ajax are the best bet here.
Any help would be greatly appreciated.
Okay, here an example for a very simple like mechanism.
NOTE:
This example use jQuery.
For simplicity there is no Database, as db it use a simple json store.
There is no "unlike" function, it always increase the likes...
First we need our Gallery Markup:
<ul>
<li><a class="likeLink" data-imageid="1"><img src="https://dummyimage.com/100x100/000/fff" /><span class="likes">0</span></a></li>
<li><a class="likeLink" data-imageid="2"><img src="https://dummyimage.com/100x100/000/fff" /><span class="likes">0</span></a></li>
<li><a class="likeLink" data-imageid="3"><img src="https://dummyimage.com/100x100/000/fff" /><span class="likes">0</span></a></li>
<li><a class="likeLink" data-imageid="4"><img src="https://dummyimage.com/100x100/000/fff" /><span class="likes">0</span></a></li>
</ul>
data-imageid: This is our reference for the likes set on an image
< span class="likes" >: just a litte container that show likes for an image
Now we need a "store", in this example case a simple json object:
{
"images":[
{"imageId":1,"likes":0},
{"imageId":2,"likes":0},
{"imageId":3,"likes":0},
{"imageId":4,"likes":0}
]
}
Next we need is a bit JavaScript:
$(document).ready(function(){
// Initial loading likes for images
$.ajax({
type: 'GET',
url: 'setlike.php?getAllLikes',
success: function (data) {
$.each(data.images, function(index, value){
$('.likeLink[data-imageid="'+ value.imageId +'"]').find('.likes').html(value.likes);
});
}
});
// Set a like for an image
$('.likeLink').on('click', function(){
var imageId = $(this).attr('data-imageid');
$.ajax({
type: 'POST',
url: 'setlike.php',
data: { imageId: imageId },
success: function (data) {
$('.likeLink[data-imageid="'+ data.imageId +'"]').find('.likes').html(data.likes);
}
});
})
})
Last but not least, we need a php script that handle our ajax requests:
header('Content-Type: application/json');
$data = file_get_contents('store.json'); // In this file is our json object
if(isset($_GET['getAllLikes'])) {
echo $data;
}
if(isset($_POST['imageId']))
{
$jsonObj = json_decode($data);
$likedImg = null;
foreach($jsonObj->images as $v)
{
if($v->imageId == $_POST['imageId'])
{
$v->likes++;
$likedImg = $v;
}
}
file_put_contents('store.json', json_encode($jsonObj));
echo json_encode($likedImg);
}
I have this code where you click a button to upload multiple files. When user have select the images, it will automatically upload the files, then preview show the uploaded files. But this error appeared when preview list appear (sometimes few images loaded successfully).
I'm using Ajax and Form Data to send the images, return an array of successful uploaded image's names, and append preview div when completed. The image upload is working fine, so here's my code on the Ajax success return:
$.ajax({
url: 'process.php',
type: 'POST',
data: form_data,
dataType: 'json',
async: false,
success: function (data) {
if(data){
$.each(data, function(index, value) {
var img = "'../content/"+brand+"/"+category+"/"+value+".png'";
$('<li id="product-'+value+'" class="product item-flex-2"><div class="list-menu border-bottom"><i id="delete-product-'+value+'" class="fa fa-remove pointer color-red-hover"></i></div><div id="img-'+value+'" class="img-wrapper" style="background-image:url('+img+')"></div></li>').insertBefore($('#product-new'));
$('#upload-product').val();
});
} else {
alert('Upload Failed.');
}
},
cache: false,
contentType: false,
processData: false
});
Here's the code on PHP file that process upload file:
$product = array();
$brand = $_POST['brand-owner'];
$category = $_POST['category'];
$res_dir = '../content/'.$brand.'/'.$category.'/';
$count = count($_FILES['upload-product']['name']);
$last_file = count(array_diff(scandir($res_dir), array('..', '.', 'index.html')));
$html_dir = $res_dir.'index.html';
for ($i = 0; $i < $count; $i++) {
$last_file++;
$tmp_file_name = $_FILES['upload-product']['tmp_name'][$i];
$new_name = $res_dir.str_pad(($last_file),3,0,STR_PAD_LEFT).'.png';
$create_png = imgToPng($tmp_file_name);
if(imagepng($create_png, $new_name)){
array_push($product,str_pad($last_file,3,0,STR_PAD_LEFT));
}
}
generateHTML($html_dir, 'product', $brand, $category);
echo json_encode($product);
Here's imgToPng function code (if needed):
function imgToPng($tmp_file_name) {
$create_png = imagecreatefromstring(file_get_contents($tmp_file_name));
imageAlphaBlending($create_png, true);
imageSaveAlpha($create_png, true);
return $create_png;
}
I also have preview menu with similar code as above, and the error also appear there. I've tried CTRL + F5 to force refresh but it only works after few attempts. I've searching look around but most is about Firefox's Bug (i'm on 48.0.2) or the error is on img tag. I have another html page that use img tag and show no error, but i need to use div on this page.
Thank you...
Update : It looks like the image is corrupt after converted to png. I tried with original extension and the images load correctly. So either my code is incorrect or something wrong with PHP function.
I am trying to make an image upload where the JavaScript posts DataURI of an image via AJAX and the PHP receives it to decode it into an image.
The problem is, everything is working fine except that the end product is not an image file.
Please have a look at the following example code.
JavaScript:
dataString='encodedimg='+e.target.result.match(/,(.*)$/)[1]+'&type='+type;
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
data: dataString,
success: function(data){
//print success message
});
PHP:
$encodedimg = $_POST['encodedimg'];
file_put_contents('asdf.png', base64_decode($encodedimg));
There is no problem with $_POST['encodedimg'] as it produces the right image using online base64 converter. So I am assuming that there is a misuse with file_put_contents() or base64_decode().
Appreciate the help!
To read image on PHP i used a function like this
function rcd($data) {
$p = strpos($data, ',');
$d = base64_decode(substr($data, $p+1));
$rfn = md5(mt_rand(1,123123123));
file_put_contents($rfn, $d, LOCK_EX);
return $rfn;
}
Usage example:
$img_file_name = rcd($_POST['image_data']);
On JS part it is tricky (different browsers, etc). First of all You need to have the image data. Now You do not precise how this is sourced and the code example does not give a hint. We can assume some options
Simple You get dataString properly populated by whatever means neccesary, then Your example should basically work
imgdata = .... // any means of getting the data
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
});
Not so simple You have a Canvas object on the screen which was populated by any means and You want to send that data. Whatever above is true, however the way to get image data would be
var canv = document.getElementById('id_of_canvas');
imgdata = canv. toDataURL('image/jpeg', 0.88); // last arg is quality
However, as some browsers (mobiles) might not be so lucky to support this, you might want to find JPEGEncoder for JS and add it, along with the code below, to Your project.
var tdu = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function(type,param1)
{
var res = tdu.apply(this,arguments);
if(res.substr(0,11) != "data:image/")
{
var encoder = new JPEGEncoder();
return encoder.encode(this.getContext("2d").getImageData(0,0,this.width,this.height), (param1 ? param1*100 : 88));
}
else return res;
}
Hope this helps!
FOr #Marcin Gałczyński:
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
}
})
I think jQuery.ajax didnt have image_data jQuery.ajax
So I'm making a website for a client, and the client has tons of photos from tons of different bands they photographed in the 80s and 90s that they would like to try and sell.
Instead of making a page for each band (theres over 100) like the previous site did, I am trying to make one page that uses Javascript/PHP to change the image directory to that band when the text for that band is clicked.
So far, I am able to use a PHP function to find photos in the slideshow folder, but I have been unable to update this function to search through a sub directory in the slideshow folder. (For example, when 'Metallica' is clicked, I empty #imageGal, and then I would like to append all the new metallica images from the metallica folder to the gallery).
My PHP code is:
<?php
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
This PHP code seems to work great.
I get the images using this JQuery code:
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
When a user clicks on a band (ie Metallica), this code is executed.
$('.options').mousedown(function() {
var name = $(this).attr('id');
//$('#output').html(name);
$.ajax({
type: "POST",
url: "slideshow/getimages.php",
data: {
imageDir: name
}, success: function(msg){
alert( "Data Saved: " + msg );
}
});
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
});
I am unable to get the $imagesDir variable to change, but if I were to manually enter "Metallica" in $imagesDir = "Metallica" variable, it loads those images perfectly.
Can anyone offer any help/advice? I've been at this for a many hours now. Thanks for anything!
Unless you have register_globals on then you need to reference the variable through the global $_POST array. $_POST['imagesDir'] instead of $imagesDir.
However I would state in it's current form it would be a very bad idea to simply replace it as someone could attempt to exploit your code to list any directory on the server.
You should append the parent directory to prevent an exploit. Something like this:
EDIT you have to chdir() to the path before glob will work. I've updated my code below.
<?php
$imagesDir = $_SERVER['DOCUMENT_ROOT']; // this is the root of your web directory
$images = array();
// and this line ensures that the variable is set and no one can backtrack to some other
// directory
if( isset($_POST['imagesDir']) && strpos($_POST['imagesDir'], "..") === false) {
$imagesDir .= "/" . $_POST['imagesDir'];
chdir($imagesDir);
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
}
echo json_encode($images);
?>
I'm not an ajax expert but you seem to be posting imageDir.
So your PHP code should be looking for $_POST['imageDir'].
<?php
$imagesDir = $_POST['imageDir'];
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
Does this solve it?
I'm looking for a php script server side that load an image in a div on client side.
first shot:
ajax.php
if((isset($_POST['id'])) && ($_POST['id']=="loadphoto") && (ctype_digit($_POST['idp']))) {
$query=mysql_query("SELECT articleid, photoid FROM articles_photos WHERE id='".$_POST['idp']."'", $mydb);
if(mysql_num_rows($query)!=0){
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
$path="./articles/photos/".$row[0]."/".$row[1];
}
echo $path;
}
}
myjs.js
function loadPhoto(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'idp='+escape(mexid)+'&id=loadphoto',
success: function(msg) {
$('.articleviewphoto1').find("img").each(function(){
$(this).removeClass().addClass('photoarts');
});
$('#'+mexid).removeClass().addClass('photoartsb');
$('#visualizator').html('<img src="'+msg+'" class="photoartb" />');
}
});
return false;
}
Are you looking to host a list of possible images in the PHP file and load different images based on the id you send? If so, you can set:
$Img = $_POST['idp'];
And use a switch statement to pass back the image file path:
switch ($Img){
case (some_value):
echo 'images/some_file.jpg';
break;
case (another_value):
echo 'images/another_file.jpg';
break;
}
Then place the file path in an tag and load that into $('#visualizator').html();
Am I on track at least with what you want? If so, I can flesh the answer out a bit.
I'm assuming the image already exists somewhere and isn't being generated on the fly. In the PHP script, you can access the variables with $_POST['idp'] and $_POST['id']. Do whatever processing you need, and then simply echo the URL. The variable msg in the javascript will be everything echo'd by the PHP script. Then, you could just do this:
$('#visualizator').html('<img src="' + msg + '" />');