reading json data from a file - javascript

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/

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.

How can I find the current html filepage name using Javascript, on a LIVE-SERVER

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.

Load LOCAL JSON file in an HTML using JS (and jquery and/or AJAX); ANSWER=IMPOSSIBLE

Problem definition:
I am programming one HTML file to be run locally in a user machine NOT FUNCTIONING AS A SERVER.
A user could run this html file locally stored in his computer. The HTML file will generate a table dynamically based on the data stored in his machine locally in a particular folder (which is always the same). This data is a JSON file.
For clarity reasons asume that the JSON file is in the same folder as the HTML file.
I have been reading a lot in the internet and in stack overflow at no avail.
For instance:
a) here with:
$.getJSON("books.json", function(json) {
console.log(json);
//access your JSON file through the variable "json"
});
does not work.
Or using this code:
jQuery.getJSON("data.json", handleJSON);
function handleJSON(result){
jQuery.each(result, printFields);
}
function printFields(i, field){
let row = field.id + " "+field.first_name + " "+field.last_name + " <br>";
jQuery("div").append(row);
}
the console says:
[Error] Failed to load resource: Preflight response is not successful (data.json, line 0)
[Error] XMLHttpRequest cannot load file:///Users/jose/CODE/HTML/ConceptsHTML/example%203/data.json. Preflight response is not successful
There are several other links of Stack overflow that I could put here. None one functions as smoothly as they say they do.
(I am using a MAC and trying the HTMLs in Safari and Chrome)
Ultimately I want of course to pass the JSON to an array to be access in other scripts of the HTML.
Note: There are some solutions where it is said that the local machine has to be run as a server and an Httprequest should be done in the machine. Well I can not do that since the users can only open the html file but nothing can be expected from them as to set the machine as as ever whatsoever.
I would be very very glad If I get a hint as to how to proceed. Right now I don't even know if this is actually possible to do.
thanks a lot
You could just use another JS file and link to it in your HTML file, and then in that JS file just make an object with the data you want.
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
function fun(){
alert(json.data);
}
</script>
</head>
<body>
<button onclick="fun();">push me</button>
</body>
</html>
JS (json.js):
var json = {
data : "hello world"
};
Linking to a local JSON file cannot be done.
THE ANSWER IS:
IT IS NOT POSSIBLE TO READ LOCAL FILES (FILES IN THE USER MACHINE) WITH HTML DUE TO SECURITY REASONS.
The funny thing is that there are plenty of post telling the contrary.
I UNDERSTAND THAT IF THAT WOULD BE POSSIBLE SENSIBLE DATA MIGHT BE STOLEN.
The improvement for html future versions would be to create a way for the local. User to tell the local browser which local folder is "free" to be accesible by html.
At first, you need to parse loaded json file, because before parsing, the content is just string and you can not handle it.
So please do as below:
function handleJSON(result){
result = JSON.parse(result); // using json.parse function to convert string to a valid json model.
jQuery.each(result, printFields);
}
I hope it will be helped you.

HTML 5 anchor tag download incomplete file?

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.

Executing a JavaScript file directly from the browser

This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.

Categories