ajax can't find url of a folder/directory (404) - javascript

I have some ajax that returns a 404 when trying to find a folder full of images that definitely exists. I tried using the solutions here but nothing worked.
var folder = "img/macro";
$.ajax({
url : folder,
success: function (data) {
// add images to html
}
});
It makes no sense because everything works perfectly locally, but when I push it up to GitHub Pages the console says that https://example.com/img/macro/ doesn't exist when you try to run that ajax. Yet I can easily just navigate to that location in the address bar with an image filename appended: https://www.example.com/img/macro/image.jpg
How do I get the ajax to find this folder of images? Is this a .htaccess problem?
The reason I'm doing this is because I have about 50 images in the folder of img/macro that are being procedurally appended into the html so that I don't have to create 50 html elements with unique file names. This way I can just dump all my images into one folder and just have ajax grab them all.

Related

Image files not loading through jquery ajax from server cpanel

I don't know if this is a duplicate question but i have searched and couldn't found solution for this
I am newbie in cpanel and i recently uploaded my project in it. Now there is a part in my website where i am loading a folder of images through jquery ajax. Now this was working perfectly in the local server xampp but not in the server it keeps giving 404 error that means that the files not being discovered by the ajax script. For security reasons i am not going to share the links right now but i will explain the full procedure
These are the location of those folders. These scripts are in js folder. But obviously it is included in index page. anyway lets move
var svgFolder = "img/svg/";
var productImagesFolder = "img/ImagesForProducts/";
Following are the ajax scripts that i am using to load the images of these folders
$.ajax({
url: svgFolder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|svg)$/)) {
$(".svg-shapesDiv").append("<img src='" + svgFolder + val + "' id='svg-shapes' loading='lazy'>");
}
});
}
});
$.ajax({
url: productImagesFolder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|jpg)$/)) {
$("#avatarlist").append("<img style='cursor:pointer;' class='img-polaroid' src='" + productImagesFolder + val + "' loading='lazy'>");
}
});
}
});
All of this is working fine in localhost server but for some reason when i uploaded them in the cpanel it stopped working.
I tried hard coding the img tag like this
<img src='img/svg/file.svg' id='svg-shapes' loading='lazy'>
<img src='img/ImagesForProducts/file.png' id='svg-shapes' loading='lazy'>
Things i tried
And this works fine so i think that the ajax is not figuring out the address. I also tried to search the image through link in the browser like this domainname.com/img/svg/file.svg and it works fine as well. i also tried to give ajax the path like this domainname.com/img/svg/file.svg but it doesn't work. I checked the file capitalization etc but everything is correct
If this was a stupid question then i am sorry but i don't know that what i am doing wrong and i am also new to cpanel and live hosting stuff.
Based on the response to my comment it sounds as though your xampp has "indexes" enabled by default. Please see here: https://httpd.apache.org/docs/2.4/mod/mod_autoindex.html
It may be that on your shared webhosting they are disabled by default and you would need to enable them for those 2 directories. As you are using cpanel please see here: https://docs.cpanel.net/cpanel/advanced/indexes/82/ but this can also be achieve by adding a .htaccess file to the 2 folders containing Options +Indexes.
The trouble with relying on indexes this way is that different servers could potentially return slightly different html so you could find that your xampp server returns html links (your JavaScript searches for anchor tags and gets the href from there) but the shared server may not return links it may just return the file names. Also with this html being returned your JavaScript has to parse that html, search all links and extract the href. I would therefore recommend writing a php script that gathers the relevant files and returns only those in JSON format. Much easier then for the JavaScript to parse and use and you now have full control of what is returned whether it is on your xampp server or other hosting. You can call this script whatever you want and you can place it wherever you want. You could even have one script that accepts query parameters from your AJAX call and from those it know which folder to look into and what types of files it must gather from the folder. This also has the advantage of keeping all other files in those folders hidden from prying eyes.

Ajax url GET 404 error

I'm trying Ajax on loading all pictures inside one local folder onto my html page. Code references this question. Files run on (Tomcat 8.5) server in Eclipse first and I open url in Google Chrome. Then Ajax fails according to the console:
GET /Users/jiaqni/.../WebContent/upload 404 ()
Any idea what I did wrong? Relative path "dir='upload/';" neither works. Thanks guys!
<script>
$(document).ready(function(){
console.log("Image appending...");
var dir = "/Users/jiaqni/.../WebContent/upload/";
var regexp = new RegExp("\.png|\.jpg|\.jpeg");
$.ajax({
url: dir,
success: function (data) {
//List all .png .jpg .jpeg file names in the page
console.log("Success!");
$(data).find("a").filter(function(){return regexp.test($(this).text());}).each(function(){
var filename = this.href.replace(window.location, "");
...
});
}
});
});
</script>
.htaccess was added to folder /User/.../upload/ to ensure it's browsable. And without Ajax, <img src="upload/xxx.jpeg"/> does display image in that folder.
I am guessing that the URL in question here refers to a local resource on your computer.
Unfortunately, this is not possible - usually browsers (e.g., Google Chrome) prevent you from doing so (due to privacy & security issues that may arise by allowing it).
You should put your files in your web server (e.g., Apache, ngnix, etc.) and adjust the URL of the AJAX request accordingly.
Good luck.

jQuery AJAX Cannot Find Local File in WordPress Installation

I'm having trouble with a WordPress plugin I've been working on. A JS file is loaded as a resource with each page/post opened, which in turn has a request to load the contents of an HTML file.
Being that the page/post directories change frequently, I'm having a difficult time making the jQuery dynamically pin down the location of the file (even though it's in the same location as the rest of the plugin resources).
An example:
jQuery('body').append('<section id="asub00LOAD"></section>');
var url = jQuery(location).attr('hostname');
var dir = url + '/wp-content/plugins/adsenseunblock/html/adunblock.html #asub00AJAX';
jQuery('#asub00LOAD').load(dir);
That was placing the whole URL path to the file after the local install ("root.com/CHEETOS/" in this case):
After which, I did this, which works fine for the root directory only:
jQuery('body').append('<section id="asub00LOAD"></section>');
var dir = 'wp-content/plugins/adsenseunblock/html/adunblock.html #asub00AJAX';
jQuery('#asub00LOAD').load(dir);
After you venture to another page, obviously the directory location is wrong again.
I tried to place some PHP into my JS file before so I could take advantage of the $plugins_url feature, but that became very convoluted and it's hard to track any errors without a PHP console to work from...
I hope someone here will have a solution for me!
The first example probably fails because there's no http:// (or //)
Use var url = "//" + location.hostname;
The second example should work everywhere if you use a root-relative path:
var dir = '/wp-content/plugins/adsenseunblock/html/adunblock.html #asub00AJAX';

Chrome extension: move downloaded file to input field

I am trying to migrate images with a small chrome extension i have built. the extension consists of 5 files:
popup.html - the plugin html document
Has some html buttons
also has script link to my settings.js file that listens for the image downlaod button to be clicked and send a message to my content script : run.js to find the images
run.js - content script ( has access to the webpages DOM ).
This script recieves the message from run.js which then finds all the images names and image links i want to download. It puts them into an object and sends them via message to the backgorund script : bootstrap.js
bootstrap.js - runs the background page and has access to the chrome api.
var Downloads = [];
chrome.extension.onMessage.addListener(function(request, sender, sendResponse)
{
if(request.message.method == 'download'){
for( var d = 0; d <= request.message.imageLinks.length; d++ ){
chrome.downloads.download( {url: request.message.imageLinks[d],
filename: request.message.imageName[d]}, function(id){
});
sendResponse('done');
}
}
});
This all works fine and dandy. It loops through the images and downloads them.
What i need to be able to do now is: Take the images i just downloaded, and insert them into the file upload fields on the other website (which i have open in another tab) which have the same field names ect..
I see chrome has a
//Initiate dragging the downloaded file to another application. Call in a javascript ondragstart handler.
chrome.downloads.drag(integer downloadId)
At first i thought this might work since you can manually drag the downloaded image into the html file upload field without having to click and select the file. But i can't find any documentation / examples on it.
Does anyone know it is possible to get accomplish this with javascript / chrome api?
First you need to access the content of the files you downloaded.
For that, you need to add a permission to file://*in your manifest file.
Then you can loop through your downloaded files with chrome.downloads.search for instance and get each file's path in the system (DownloadItem.filename property). For each file, make a GET XMLHttpRequest to the url file://{filepath} to get the file's content.
Once you have that content, you can convert it to a DataUrl and programmatically add the file to the FormData of your form (not the actual inputs though, just the FormData submitted in the end). See this answer for this part.

check if folder exists in the root jquery

I'm trying to load an image to a div background using the following file structure in the root.
WebContent --
|
zharaimages --
|
[ItemID] --
|
Image.jpg
This is done by jQuery and the file structure is inside the root. The ItemID folder is dynamic and I have to check whether the path exists using jQuery and if the path is not valid, I should go to a default path to fetch the default image. How can I check the path is valid using jQuery. I'm hoping to this can be done without an ajax call.
Can any one help me on a tutorial or an API I can use for this!
UPDATE
The files are on the server. The concept I have is that I have 100s of item elements & I want to load an image for each item element. The images are saved in the server ( a local host ) and the folder hierarchy is divided using the item ID as shown. What I want to do is check whether the image file exists before appending it to the background of the item element div. Is this possible. This is a web application developed using spring.
In simple way you cannot. It is because JavaScript cannot access folders on server side. The only way you could try to check is to invoke $.get in which you pass url to image and handle error if image does not exist. You cannot try to get only folder because if folder listing is disabled you will always get error
you can bind error handler on your image tag, and if error receive you can load your default image.
$('#imgElementID').error(function() {
$(this).attr('src', 'images/DEFAULT.JPG');
});
without hitting URL you cannot get to know if image exist or not

Categories