loading images from e folder and display them in html - javascript

Hi guys by using the following code I am trying to read all images from a folder and then to display them in my html file. The problem is how you can see the /images/ folder is in /fetch/ folder. When the images are displayed are loaded like /fetch/frame_1.jpg instead /fetch/images/frame_1.jpg so in this case to display them I have to use twice the images set. One in the image folder and one in the fetch folder. Can anyone explain to me why is this?
<body>
<script type="text/javascript">
var dir = "/fetch/images/";
var fileExtension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileExtension + ")").each(function () {
var fileName = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='"+ fileName + "'>");
console.log(fileName);
});
}
});
</script>
</body>

Two changes got me images.
1) remove forward/back slash from var dir.
2) combining dir and name of file.
Below is the code that worked for me:
<body>
<script type="text/javascript">
var dir = "fetch/images/";
var fileExtension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileExtension + ")").each(function () {
var fn = this.href.replace(/^.*[\\\/]/, '');
var fileName = dir + fn;
$("body").append("<img src='"+ fileName + "'>");
console.log(fileName);
});
}
});
</script>
</body>

Related

single and multiple file upload

I'm facing issue. single and multiple file uploaded file. Then multiple file upload successfully but when single file one by one upload then last one upload other are override by last one. Please help me to find out this problem solution. As you can see below code it's work properly for multiple upload file and send data by ajax then get array value all images but when upload single upload one by one then last one image data get only in ajax data in. please help me to provide me solution.
index.php
`
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
</style>
<body>
<form id="myForm" method="post">
<input type="file" id="files" class="file_uploader_file" name="files[]" multiple="true" accept="image/*" />
<p class="validateError" id="imgerror" style="color:red;display:none;">Please select your design.</p>
<input type="button" id="fees_stream_submit1" name="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
(function () {
$(document).on('click', '#fees_stream_submit1', function (e) {
var myfiles = document.getElementById("files");
// var myfiles = $('#files').val();
var files = myfiles.files;
var form = new FormData();
alert(files.length);
for (i = 0; i < files.length; i++) {
form.append('file' + i, files[i]);
}
$.ajax({
url: "fileuploadmultidata.php",
type: "POST",
data: form,
contentType: false,
processData: false,
success: function (result) {
// alert(result);
}
});
});
})();
$(document).ready(function () {
var imgCnt = 0;
var onebyoneImg = [];
var countImg = 1;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
// var f = new File([""], files[i]);
var fileReader = new FileReader();
fileReader.onload = (function (e) {
imgCnt++;
alert(imgCnt);
var file = e.target;
$("<span class='pip'><div class=\"file_uploaded_view img-thumb-wrapper image-preview-height\">" +
"<img class=\"img-thumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\" style='heigh:100px;width:100px'/>" +
"<br/><span class='remove'><i class='fa fa-trash'></i></span></span>" +
"</div>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".img-thumb-wrapper").remove();
imgCnt--;
});
});
fileReader.readAsDataURL(f);
}
console.log(f);
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
</body>
</html>
`
**fileuploadmultidata.php**
`<?php
echo "<pre>";
print_r($_FILES);die();
?>`
The behaviors of file uploading will be like that only see https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
To achieve your requirement you need to store file values in variable and use.
var storeMultiFiles = [];
var file = $(file_id)[0].files;
for(var l=0; l<file.length; l++){
var fileData = file[l];
(function(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(oFREvent){
storeMultiFiles.push(oFREvent.target.result)
};
})(fileData);
}
Use files details using "storeMultiFiles" for show, save, update and delete for selected.

Importing header file in html file is not working properly

I have a header.html and header.js files because I want to use the same header through my webpages.
In header.js file, on window load I want it to console.log("header file loaded").
I also have index.html and index.js file for my homepage. In index.js, on window load I want it to console.log("index file loaded")
I called header.html in index.html file, in order to import the header for the homepage. This works fine.
based on js files the console output should
header file loaded
index file loaded
The problem I am having is that
it seems like header.js and index.js cannot work simultaneously
only the last referenced file gets outputed in the console
for example this format
<script src="js/header.js"></script>
<script src="js/index.js"></script>
will output
index file loaded
and this
<script src="js/index.js"></script>
<script src="js/header.js"></script>
will output
header file loaded
I use the code to import header.html in index.html
<head>
<div data-include="header"></div>
</head>
<body>
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
</body>
this is the content of both js file
function retrieveInfo(data) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Sellers/' + userId).once('value').then(function(snapshot) {
console.log(userId)
console.log("index file loaded")
});
}
})
}
what am I doing wrong and how can I fix it to have both js file called?
You are doing it in a wrong way, .load() is used for loading HTML contents. You should be using .getScript(), to load the js and execute it.
According to docs:
.load()
Load data from the server and place the returned HTML into the matched element.
.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Here is an example for using getScript:
$.ajax({
url: url,
dataType: "script",
success: function() {
alert("script loaded");
}
});
In your case it would be:
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var JS = $(this).data('include') + '.js';
var file = $(this).data('include') + '.html';
$(this).load(file);
$.ajax({
url: JS,
dataType: "script",
success: function() {
alert(file + " loaded");
}
});
});
});

jquery ajax load images from local folder

I want to get pictures from a local folder and post them on a webpage.
Pictures aren't loading on webpage but no errors in console.
<head>
<title> </title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var dir = "/Users/me/Desktop/imgtest/";
var fileextension = ".jpeg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
</script>
</head>
<body>
This can't be running cos you page isn't loading.
You should add this script before the end of your body or use $(document).ready to be sure you page is loading before to call the Ajax script.
<script type="text/javascript">
var dir = "/Users/me/Desktop/imgtest/";
var fileextension = ".jpeg";
$(document).ready(function(){
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
});
</script>
Wrap your script code in a document ready function, like so:
$(document).ready(function() {
// your code here
});
Then, run a local web server to avoid XSS issues.

Get A Script To Work Using hostname To Grab URL

I'm trying to figure out how to get this script to work and it's frustrating. I'm trying to improve the script by grabbing the URL instead of entering the domain manually.
Here is the original:
<script type='text/javascript'>
makeSlider({
url: "http://yourdomain.com/" // Add your blog URL
});
</script>
Here is what I tried(and others similar to it):
<script type='text/javascript'>
makeSlider({
url: "http//" + window.location.hostname + /
});
</script>
I even tried using a variable:
<script type='text/javascript'>
var getDomain = "http//" + window.location.hostname + /,
makeSlider({
url: getDomain
});
</script>
None of my attempts have worked.
Try
var getDomain = "http://" + window.location.hostname + "/";

Can I load images from a folder?

I got the snippet online:
<html>
<head>
<title></title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
var dir = "";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function ()
{
var filename = this.href.replace(window.location.host, "").replace("http:///", "");
$("body").append($("<img src=" + dir + filename + "></img>"));
});
}
});
</script>
</body>
</html>
But when I try to run this nothing happens. The images are in the same folder (on my Desktop) where the .html file. But can I do this with javascript, or do I need some backend like PHP/ASP.NET or something?

Categories