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.
Related
I am going to deploy this page on an FTP
And I need to find out how I can detect the html file currently being viewed using JavaScript.
If I open the html file, it works just fine with this:
var fileName = location.href.substring(location.href.lastIndexOf("/") +1);
But, if I open it via my localhost adress, it has a null value. So I'm guessing I have to use some other method to extract the current html file name. Or is there a better approach to this?
Note: I am not going to use JQuery or anything like that.
EDIT:
I can get the filename if it isn't my index file.. If it's the index file I get nothing using the above code. Most likely since all I have in my adress bar is the localhost adress of the live-server?
The web deals in URLs, not file names.
Sometimes a URL will include something that looks like a file name, and sometimes that even maps on to a real file name on the server's hard disk.
When you type http://example.com/ then it might map that onto a file called index.html. Or maybe on to index.php. Or maybe it won't touch any file but will just use logic built into the web server application to determine what to respond with.
There's no way to know in the general case.
If your specific case, you know that the path / maps onto index.html, so you can write an explicit mapping in your JavaScript code.
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.
I am using angular and ASP.NET Web API to allow users to download files that are generated on the server.
HTML Markup for download link:
<img src="/content/images/table_excel.png">
<a ng-click="exportToExcel(report.Id)">Excel Model</a>
<a id="report_{{report.Id}}" target="_self"></a>
The last anchor tag is there to serve as a place holder for an automatic click event. The visible anchor calls the exportToExcel method to initiate the call to the server and begin creating the file.
$scope.exportToExcel = function(reportId) {
reportService.excelExport(reportId, function (result) {
var url = "/files/report_" + reportId + "/" + result.data.Model.fileName;
var dLink = document.getElementById("report_" + reportId);
dLink.href = url;
dLink.setAttribute('download', result.data.Model.fileName);
dLink.click();
});
}
The Web API code creates an Excel file. The file, on the server is about 279k, but when it is downloaded on the client it is only 7k. My first thought was that the automatic click might be happening before the file is completely written. So, I added a 10 second $timeout around the click event as a test. It failed with the same result.
This seems to only be happening on our remote QA server. On my local development server I always get the entire file back. I am at a loss as to why this might be happening. We have similar functionality where files are constructed from a database blob and saved to the local disk for download. The same method is employed for the client side download and that seems to work fine. I am wondering if anyone else has run into a similar issue.
Update
After the comment by SilentTremmor we think it actually may be IIS or some sort of Sever issue. Originally, we didn't think it could be, but after some digging it may be. It seems the instance of the client code is only allowing 7k of data to be downloaded. It doesn't matter what we try to download the result is always the same.
It turns out the API application was writing the file to a different instance of our application. The client code had no idea and was trying to download a file that did not exist. So, when the download link was creating the file it was empty, thus the small file size.
So I've been researching this for a couple days and haven't come up with anything conclusive. I'm trying to create a (very) rudimentary liveblogging setup because I don't want to pay for something like CoverItLive. My process is: Local HTML file > Cloud storage (Dropbox/Drive/etc) > iframe on content page. All that works, and with some CSS even looks pretty nice despite the less-than-awesome approach. But here's the thing: the liveblog itself is made up of an HTML table, and I have to manually copy/paste the code for a new row, fill in the timestamp, write the new message, and save the document (which then syncs with the cloud and shows up in the iframe). To simplify the process I've made another HTML file which I intend to run locally and use to add entries to the table automatically. At the moment it's just a bunch of input boxes and some javascript to automate the timestamp and write the table row from the input data.
Code, as it stands now: http://jsfiddle.net/LukeLC/999bH/
What I'm looking to do from here is find a way to somehow export the generated table data to another .html file on my hard drive. So far I've managed to get this code...
if(document.documentElement && document.documentElement.innerHTML){
var a=document.getElementById("tblive").innerHTML;
a=a.replace(/</g,'<');
var w=window.open();
w.document.open();
w.document.write('<pre><tblive>\n'+a+'\n</tblive></pre>');
w.document.close();
}
}
...to open just the generated table code in a new window, and sure, I can save the source from there, but the whole point is to eliminate steps like that from the process.
How can I tell the page to save the generated code to a separate .html file when I click on the 'submit' button? Again, all of this happens locally, not on a server.
I'm not very good with javascript--and maybe a different language will be necessary--but any help is much appreciated.
I suppose you could do something like this:
var myHTMLDoc = "<html><head><title>mydoc</title></head><body>This is a test page</body></html>";
var uri = "data:application/octet-stream;base64,"+btoa(myHTMLDoc);
document.location = uri;
BTW, btoa might not be cross-browser, I think modern browsers all have it, but older versions of IE don't. AFAIK base64 isn't even needed. you might be able to get away with
var uri = "data:application/octet-stream,"+myHTMLDoc;
Drawbacks with this is that you can't set the filename when it gets saved
You cant do this with javascript but you can have a HTML5 link to open save dialogue:
<a href="pageToDownload.html" download>Download</a>
You could add some smarts to automate it on the processed page after the POST.
fiddle : http://jsfiddle.net/ghQ9M/
Simple answer, you can't.
JavaScript is restricted to perform such operations due to security reasons.
The best way to accomplish that, would be, to call a server page that would write
the new file on the server. Then from javascript perform a POST request to the
server page passing the data you want to write to the new file.
If you want the user to save the page to it's file system, this is a different
problem and the best approach to accomplish that, would be to, notify the user/ask him
to save the page, that page could be your new window like you are doing w.open().
Let me do some demonstration for you:
//assuming you know jquery or are willing to use it :)
var html = $("#tblive").html().replace(/</g, '<');
//generating your download button
$.post('generate_page.php', { content: html })
.done(function( data ) {
var filename = data;
//inject some html to allow user to navigate to the new page (example)
$('#tblive').parent().append(
'Check your Dynamic Page!');
// you data here, is the response from the server so you can return
// your new dynamic page file name here.
// and maybe to some window.location="new page";
});
On the server side, something like this:
<?php
if($_REQUEST["content"]){
$pagename = uniqid("page_", true) . '.html';
file_put_contents($pagename, $_REQUEST["content"]);
echo $pagename;
}
?>
Some notes, I haven't tested the example, but it works in theory.
I assume that with this the effort to implement it should be minimal, assuming this solves your problem.
A server based solution:
You'll need to set up a server (or your PC) to serve your HTML page with headers that tell your browser to download the page instead of processing the HTML markup. If you want to do this on your local machine, you can use software such as WAMP (or MAMP for Mac or LAMP for Linux) that is basically a web server in a .exe. It's a lot of hassle but it'll work.
I am running a server with Go programming language, and when I load the server in the browser, the temp handler function is called and the getjson.html file is served by this temp Handler function. Now the screen shows a "Get Json Data" button. On clicking this button, I am not getting any results (as something should be displayed on the screen).
I checked the javascript console and there are no errors as such.
I am not able to figure out what the problem is, why isn't there any output on the screen.
Contents of servejson.go :
package main
import (
"http"
"flag"
)
var path = flag.String("root", "/home/chinmay/work/json/getjson.html", "Set root directory, use absolute path")
func temp(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
http.ServeFile(w,r,*path)
}
func main(){
http.HandleFunc("/",temp)
http.ListenAndServe(":8080", nil)
}
Contents of getjson.html :
package main
import (
"http"
"flag"
)
var path = flag.String("root", "/home/chinmay/work/json/getjson.html", "Set root directory, use absolute path")
func temp(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
http.ServeFile(w,r,*path)
}
func main(){
http.HandleFunc("/",temp)
http.ListenAndServe(":8080", nil)
}
Contents of json_data.js:
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
Yes, you can. Live example. Provided that json.txt is a resource next to the document in which this code is running, and (on some browsers) provided this is not running from a local file (e.g., a file:// URL rather than an http:// one; some browsers are okay with local files accessing other local files via ajax, others are not).
A couple of notes:
In the
$("div").append(field + " ");
line, field will be the value of each property (e.g., "John").
The order in which the properties are listed is completely undefined.
So for this specific example, you'd probably be better off with
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("json.txt",function(result){
$("div").append(result.firstName + " " + result.lastName + " " + result.age);
});
});
});
</script>
Live example
Update: From your comments on another answer, it seems like you might be unclear on where and how the script code is running. The JavaScript script runs on the client's browser. The path to use to reference json.txt is exactly like (say) the path to an image you want to show on a page. json.txt must be accessible via the web server, just like an image would need to be accessible via the web server. Think of json.txt as just another resource used by your web page, like any other. In terms of the path, and how you have to make json.txt available, the same rules apply. To be clear: Script running client-side in a web page cannot access a server-side file that can't be retrieved by the browser.
Update 2: You've posted more code, and it looks like you've made your server only serve the getjson.html file. Your server also has to serve the json.txt file, or the browser can't access it.
Sorry if this isn't related to Go, but I falt here while searching a solution to a similar problem in JQuery and the solution isn't related to the tool used.
I got a problem today to simulate a Json query on a program linked to a database, without the database. So I saved a Json result to a file and wanted to use it instead. The json.txt file was on a server and viewable in the browser but $.getJSON was trowing an error.
To solve this problem, all I had to do is to rename the file with an "html" extention, like json.html and to remove the header in the file. i.e. You need to NOT have "Content-Type: application/json" in the begining of your text file.
Could be specific to a web server (Apache) or browser security (Firefox) but at least it worked.
$.getJSON() needs a URL as a parameter. You are trying to access a file from the directory structure of the local machine/server which is not possible in JS.
See the jquery documentation http://api.jquery.com/jQuery.getJSON/