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?
Related
I'm new to using AJAX methods and am completely stumped with what seems like a very simple procedure.
I'm trying to post data to a php file using AJAX in order to create a folder on my server. No matter what I try it seems as if it's not actually posting data to the php file. I can end up creating a folder directly into the 'users' folder if I remove the $_POST command from the php file... but the second I try to actually create a variable from the posted data so it creates the folder inside of a nested subfolder it fails.
please please please help. I'm losing it. haha.
Someone suggested another thread to solve the problem below... but it still doesn't seem to be working. I'm using the same approach that is suggested in that thread.
Here is my script:
JQuery
<script type="text/javascript>
$('#buildSave').click(function() {
$.ajax({
url: "../php/preparesave.php",
type: "POST",
data: { user : 'Tommy' }
});
});
</javascript>
PHP
<?php
$user = $_POST['user'];
if (!file_exists('../users/' . $user . '/Platoons/')) { mkdir('../users/' . $user . '/Platoons/'); }
?>
Here is the AJAX that I suggest using
$(document).ready(function(){
$('#save').click(function() {
$.ajax({
url: '../php/preparesave.php',
type: 'POST',
data: { user : 'Tommy' },
success: function(output){
alert(output);
}
});
});
});
And below is the PHP (I tried it on my machine and it works)
$user = $_POST['user'];
if(!file_exists('../users/' . $user . '/Platoons/')){
if(mkdir('../users/' . $user . '/Platoons/', 0777, true)){
die('Success');
}else{
die("Folder `../users/{$user}/Platoons/` failed to be created");
}
}
The way you have it, it will only try to create "/Platoon" in a folder $user (Tommy in your example) but that folder doesn't exist and so the script is failing. You need to set the recursive parameter to true so it would first create the folder that doesn't exist and then everything else inside it and then them.
Allows the creation of nested directories specified in the pathname. (Straight from the docs)
There were two errors in your code. Try to compare your lines with the one below.
$('#buildSave').click(function() {
$.ajax({
url: "../php/preparesave.php",
type: "POST",
data: { user : 'Tommy' }
});
});
Try to edit your action url. Use only preparesave.php if you are calling ajax in /php folder. try to use url:"preparesave.php", if this doesnt work then use
url: "preparesave.php?user=Tommy",
Hope it could solve your issue.
THE SIMPLEST POSSIBLE ANSWER
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js</script>
<script>
var cars = ["Saab", "Volvo", "BMW"];
$(document).ready(function(){
$("button").click(function(){
$.post("test2.php",
{
cars
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>POST the cars array</button>
</body>
</html>
AND THE PHP.....
<?php
$myVar = $_POST['cars'];
$number = count($myVar);
for ($count = 0; $count < $number; $count++){
echo $myVar[$count];
}
?>
enter code here
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.
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.
I am making a http://c9.io like service to edit .php files on my server right on browser.
I have implemented CodeMirror editor there.
Editor looks following: http://codemirror.net/mode/php/index.html
My problem is that I can't send data with php code in it via jQuery.ajax POST.
Lets imagine that I would like to save following lines to hello.php:
<?php
require_once("lukujA.php");
?>
I am using following js / jquery code to save the file:
$(".save-file").click(function (){
var content = editor.getValue(); //textarea text
var path = "hello.php";
//following line shows content-data as it shows on CodeMirror editor
//confirm box without any quotes / slashes / and with every linebreak
var response = confirm("Do you want to save? DATA: " + content);
if(response)
{
$.ajax({
type: "GET",
url: "saveFile.php",
data: "content="+content+"&path="+path+"",
success: function(){
alert("File saved!");
}
});
}
else{
alert("File not saved!");
}
});
saveFile.php:
$path = $_GET['path'];
$content = $_GET['content'];
if($path !== "" and is_writable($path))
file_put_contents($path, $content);
above code outputs hello.php as something like following (on one line and with slashes)(using POST seems to remove any line breaks I made on the editor):
<?php require_once(\"lukujA.php\"); ?>
I can't use stripslashes($content); on saveFile.php cause if I have php code like:
<?php echo "<input type=\"text\" name=\"foo\">"; ?>
strip_slashes would remove those slashes and code would become invalid when executed.
How should I come across this and how should I save the new code to a file?
How would you make this kind of editor?
Thanks
Got the whole thing working with following:
$(".save-file").click(function (){
editor.save();
var content = editor.getValue(); //textarea text
var path = $("#hiddenFilePath").text(); //path of the file to save
var response = confirm("Do you want to save?");
if(response)
{
$.ajax({
type: "POST",
url: "saveFile.php",
data: {c:content,p:path},
dataType: 'text',
success: function(){
alert("File saved!");
}
});
}
else{
alert("File not saved!");
}
});
See the code data: {c:content,p:path}, dataType: 'text',
and in saveFile.php I use stripslashes($content) cause it seems I have magicquotes on on php settings.
When I need to send data like echo "<br>Edellinen Tämä viikko Seuraava<br><br>"; stripslashes still preserves those slashes before my data's quotes cause when I send data through POST like that seen above urlEncoding adds slashes before my datas slashes too.
Hard to explain. Hope someone will in future get something out of this :) Sorry for not so good english either.
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 + '" />');