i am trying to disaplay slider images dynamically by fetching all images names from slider_images folder and append it to .
<script>
var dir = "images/slider_images";
var fileextension = ".jpg";
$.ajax({
url: dir,
type: "POST",
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var url = this.href;
var filename = url.substring(url.lastIndexOf('/')+1);
//alert(filename);
$(".slides").append($("<li><img src=" + dir +"/"+ filename + "></img></li>"));
});
}
});
</script>
Finally i solve this issue by using json.
first i create getimages.php file and read directory in that file and get all images names and store that name in array.
getimages.php
<?php
$filenameArray = array();
$handle = opendir(dirname(realpath(__FILE__)).'/images/slider_images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/slider_images/$file");
}
}
echo json_encode($filenameArray);
?>
call getimages.php from page where you want load images dynamically.
index.php
$.ajax({
url: "getimages.php",
dataType: "json",
success: function (data) {
alert("success");
$.each(data, function(i,filename) {
alert(filename);
$('.slides').append('<li><img src="'+ filename +'" class="drop_shadow" alt="Slider Image 1" /></li>');
});
}
});
this is working perfectly for me. i you want please try this. this is very simple and easy way to load images from folder using ajax
Related
I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}
so I have this code to upload an image and show it's preview. It also allows you to upload multiple images and show it's preview.
However, how can I actually push this image to server now? I've tried this but it doesnt seems to be working.
HTML
<input type="file" name="albumPics" id="albumPics" style="display:none;" multiple="multiple" />
javascript
window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("albumPics");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var output = document.getElementById("albumPicsPreview");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
alert(file);
//Only pics
if(!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var liContent = "<li><img style='height: 195px;' src='" + picFile.result + "'" + "title='" + picFile.name + "'/></li>";
$("#albumPicsPreview").prepend(liContent);
// output.html(div);
// upload the image
$.ajax({
type: "POST",
url: "pettyURL.php",
data: file,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
console.log("success");
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
}); //event listener
//Read the image
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}
The ajax doesn't work here. It seems no data goes to the PHP file. How can I make it work?
I am working on an image panel that displays the image titles and a link to download the image. I have an onclick function that gathers the base64 data from the database and then 'decodes' it. However, when I decode it I'm getting back a string of Chinese text..which is obviously not what I'm looking for.
$(document).ready(function() {
$('.downloadAttachment').on('click', function() {
var documentId = $(this).attr("data-id");
console.log(documentId)
$.ajax({
dataType: 'json',
//data: id,
async: false,
type: 'GET',
//url: baseUrl + 'rest/incdDocument/getAll?branchCode=' + brCode + '&receivedDate=' + receiveDate + '&complaintID=' + cId + '&incidentID=' + incidentId+ '&documentID='+documentId,
url: baseUrl + 'rest/incdDocument/get?branchCode=009&receivedDate=03/10/2017&complaintID=170&incidentID=3'+'&documentID='+documentId,
success: function(data) {
if (data) {
var image = Base64.decode(data.data);
window.open(image, '_blank');
}
},
error: function(request, status, error) {
console.log(error)
}
});
return false;
})
});
Is there a better way to extract this data and actually turn it into an image?
Searching for like this ?
var image = new Image();
image.src = data; (complete base64 sting with imagetype)
Download Image
Make a download.php file with return the a image with
header('Content-type:image/png'); or other image type
In my data storage folder is a JSON file. I save the device id to the local storage of the broswer:
//Store deviceID in local storage on button click
function store(){
var inputDeviceID= document.getElementById("deviceID");
localStorage.setItem("deviceID", inputDeviceID.value);
}
I get the device id with a javascript function and push it with ajax into my php script to load the corresponsing data:
function localstoragecheck(){
if (localStorage.getItem("deviceID") === null) {
//alert('no');
}
else {
//alert('yes');
var deviceIDcookie = localStorage.getItem("deviceID");
$.ajax({
url: '/',
data: {'deviceID': deviceIDcookie},
dataType: 'jsonp',
complete : function(){
// alert(this.url)
$.getJSON("/sigfoxdata/" + deviceIDcookie + ".json", function(json) {
console.log(json); // this will show the info it in firebug console
});
}
});
}
}
PHP code for searching the json file and decode it:
$FOLDER = '../sigfoxdata/';
$dir = scandir($FOLDER);
$file = $_GET['deviceID'].'.json' ?: 'DEMO.json';
$fileUrl = $FOLDER.$file;
$file = fopen($fileUrl, "rip");
$lines = fread($file, filesize($fileUrl));
$data = json_decode($lines)->{'data'};
But this is not working, how can I get data from the ajax request in the PHP script?
I must pass array from JS to PHP using $.post(), create file using array and download it.
Using this pass array:
$('#csv').click(function () {
$.post(
window.location + "crawler/save_to_file",
{
dane: wynik //array
});
});
Now in PHP using this:
$tablica=$_POST['dane'];
$filename = "export-to-csv.csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Expires: 0");
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($tablica))
foreach($tablica as $row) {
if(!$heading) {
fputcsv($fh, array_keys($row));
$heading = true;
}
fputcsv($fh, array_values($row));
}
fclose($fh);
But when click on button to create and download file, nothing happens.
Thanks
CODE UPDATE
JS file:
$.ajax({
url: window.location + "crawler/",
type: "POST",
dataType: "json",
data: {
wartosc: zmienna
},
success: function (odp) {
wynik = odp; //array
tab = JSON.stringify(odp);
$.post(window.location + "crawler/return_data",
{
data: tab
},
function (data) {
$('#wynik').html(data);
$('.pobierz').show();
}
)
}
})
$('.button').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_csv" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
});
$form.appendTo('body').submit();
});
And var_dump array in PHP file:
function save_to_csv()
{
$tablica=$_GET['dane'];
var_dump($tablica);
}
return: "Undefined index: dane"
EDIT
$tablica must be $_POST not $_GET
This can be done with AJAX but you need to use the File api.
So you do something like this:
$.post("csv.php", {
dane: wynik //array
}, function(response){
var blob = new Blob([response], { type:'text/csv' });
alert(URL.createObjectURL(blob));
});
The url you get from the alert, contains your csv file.
And of course if you want to go directly to the file you replace the alert with:
window.location.href=URL.createObjectURL(blob);
UPDATE
If you want to use a custom filename, there is a way to mask the url generated by URL.createObjectURL(), by using an a element.
We than can use the new HTML5 attribute download which allows us to mask the url.
Here is the updated code:
$.post("csv.php", {
dane: wynik //array
}, function(response){
var blob = new Blob([response], { type:'text/csv' }),
a = document.createElement('a'),
url = URL.createObjectURL(blob);
// Put the link somewhere in the body
document.body.appendChild(a);
a.innerHTML = 'download me';
a.href = url;
// Set our custom filename
a.download = 'myfilename.csv';
// Automatically click the link
a.click();
});
Are you forced to use AJAX to send that array to your PHP code? If yes, it is not really possible.
If not, instead of your AJAX call, you could build a hidden form with hidden inputs containing your array items and submit it via JavaScript.
UPDATE
Short example for form built with JS:
$('#csv').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_file" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
});
$form.appendTo('body').submit();
});