Javascript: can't load JSON file from localhost - javascript

I'm currently working through the book "Head first HTML5 programming". I want to load the content of a file named sales.json from a web server on my own machine. I used wampserver for this.
In the folder wamp/www/gumball/ I put all relevant .html, .js and .css files, and also the sales.json file.
My JavaScript code is very simple:
window.onload = function() {
var url = "http://localhost/gumball/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
This doesn't do anything! Typing the link: http://localhost/gumball/sales.json in my browser opens the right file, so the link should be correct. Even when using the .js files that come with the book (with a finished version of the application I'm trying to make), nothing loads.
Testing with alert statements tells me the request.onload event never happens. I'm clueless as to why this is the case.
A fact I don't quite understand yet: when I type: http://localhost/gumball/sales.json: in my browser (I added a colon at the end of the link), I get a 403 Forbidden error! Why does this happen? Does this have something to do with my problem?

I open html document with firefox
Your HTML document must be open with a URL in http://, not file://, if you want it to be able to open in javascript another document, unless the second document is served with relevant CORS headers.
This is due to same origin policy.
As you have a local WAMP server, there is no problem : simply open your file using a http:// URL like you do for your JSON file.

Related

Fail to load .php files with ajax in Javascript

Instead of using jQuery here I am trying to use Javascript to load several .php files to
display data from the database according to the user's input. Below is an example of how my functions are like (and most of which are similar):
let userinput = document.getElementById("input");
button_1.onclick = function()
{
let xhr = new XMLHttpRequest();
xhr.open("GET", "ajax/highscore.php?q="+userinput.value, true);
// send the "username" to $_POST['q'] defined in "highscore.php"
// and then display the data according to the user's input
xhr.addEventListener("load", (event) =>
{
if (xhr.readyState == 4 && xhr.status == 200) { // display data accordingly }
});
xhr.send();
}
and below is a screenshot of the index in the server. "sample.html" is the page for displaying all the data.
However, when inspecting "sample.html", I cannot see the "ajax" folder loaded, nor any other .php files even when I changed the path "ajax/( ).php" to "( ).php". Could anyone explain why this will happen? (In the second screenshot because the parent folder contain my server's name so I covered it)
The browser dev tools (the inspect method you are using) do not list files in your server folder. It only displays files used to load your sample.html page, like CSS, JS files directly referenced (with <script> tags, and so on), etc.
Your .php files might still work, if your javascript ajax method calls them accordingly and they are reachable by the user's browser.

Open local server file using plain javascript

I want to load locally stored data using plain javascript (no jquery for example) and then use it to display it in a table in html. My project structure looks like this:
root
- js
-- main.js
- res
-- data.csv
- index.html
I tried using a XMLHttpRequest, but somehow I get status 0 when trying to load the file and when printing the response text it prints out nothing at all.
The following method is called using window.onload:
var url = "file://../res/data.csv/";
varxmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
I don't think you can access the file system through most browsers.
Even if it worked locally, it wouldn't work as soon as you put your page up on a server. This is because the client will be asking for a file that is local to itself, not the server.
Chrome may have something for you though:
https://www.html5rocks.com/en/tutorials/file/filesystem/

capture file into javascript variable instead of downloading it

I am writing a app that visits a web site that can give me a link to a file, like this: http://www.thrustcurve.org/download.jsp?id=2199
If I visit this link, a small text file is downloaded. What I would like to do instead is to capture this text into a javascript variable so I can search around in it and extract the data I need.
Is this even possible?
Further details: although I am old and have lots of programming experience, I am a total noob in the javascript/web/server/modern space (think FORTRAN 77).
I now teach high school physics and am trying to build a web-based rocket simulator for my students to use on their chromebooks. The creator of thrustcurve.org has generously made data about rocket motors available on the web, but I need some bits that can only be found inside these little text files. Maybe it would be possible to work with the downloaded files on the chrome books, but I really have no idea how to begin there. If you are patient enough to have read this far, you can see the kind of javascript I have been able to accomplish at noragulfa.com
You can use XMLHttpRequest to perform HTTP requests, but due to security restrictions the browser blocks requests to “external domains” (thus, you can download files only from your domain). For more info, read about Cross-Origin Resource Sharing (CORS).
To solve your task, you have several options:
1) Download required files from thrustcurve.org and store them on your server. This is the best option since you will not be dependent on an external server (besides, hotlinking may upset the thrustcurve.org owner). In this case XMLHttpRequest will be able to access files using relative URLs:
var url = '/thrustcurve-downloads/Estes_A8.eng';
2) Contact the thrustcurve.org owner and ask him to enable Access-Control-Allow-Origin from anywhere. In this case XMLHttpRequest will be able to access files using full URLs:
var url = 'http://www.thrustcurve.org/download.jsp?id=2199';
3) Create a proxy that passes HTTP requests to thrustcurve.org. For example, since you are using nginx, you can simple add the following to your configuration file:
location /thrustcurve {
proxy_pass http://www.thrustcurve.org/;
}
In this case XMLHttpRequest will be able to access files using relative URLs:
var url = '/thrustcurve/download.jsp?id=2199';
4) Use third-party proxies (not a very reliable solution, but great for tests). As an example, I will use this option.
var url = 'http://cors-anywhere.herokuapp.com/http://www.thrustcurve.org/download.jsp?id=2199';
var xhr = new XMLHttpRequest();
xhr.onload = function () {
console.log(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'text';
xhr.send();
UPD: A full example how to download files using a XMLHttpRequest and PHP.
1) Create the file thrustcurve.php on your root server with the following contents:
<?php
// Change this to FALSE if don't want to store files locally
$store_files_locally = true;
$id = (int) filter_input(INPUT_GET, 'id');
if ($id > 0) {
if ($store_files_locally) {
// Specify the directory where you want to store engine files
// It will create the directory if it doesn't exist
$dir = __DIR__ . '/thrustcurve-downloads';
if (!is_dir($dir) && !mkdir($dir, true, 0777)) {
http_response_code(500);
die('Cannot create the downloads directory');
}
// If file exists, load the engine from the local file
$file = "{$dir}/{$id}.eng";
if (is_file($file)) {
$engine = file_get_contents($file);
die($engine);
}
}
// Download the engine file from the remote server
$url = "http://www.thrustcurve.org/download.jsp?id={$id}";
$engine = trim(#file_get_contents($url));
// The downloaded file is considered valid engine only if it starts with semicolon
if (strpos($engine, ';') === 0) {
if ($store_files_locally) {
file_put_contents($file, $engine);
}
die($engine);
}
}
http_response_code(404);
echo "File #{$id} not found";
2) To download files using JavaScript, use the following:
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.response);
} else {
console.error(xhr.response);
}
};
xhr.open('GET', '/thrustcurve.php?id=2198');
xhr.responseType = 'text';
xhr.send();

By-pass virus scan for Google Drive links and get the confirm ID

With some help from this thread I came up with the code below. How can I fetch the Google Drive file ID, open the direct link to the file and snatch the virus scan confirm ID that is required to stream files over 100 MB and then puzzle back the link? I'm kind of stuck at the xhr part.
function fixGoogleDriveURL(url) {
if (url.indexOf('drive.google.com') !== -1) {
var DocIDfull = url;
var DocIDstart = DocIDfull.indexOf('open?id=');
if (DocIDstart == -1) {
// invalid
return url;
}
var DocID = DocIDfull.slice(DocIDstart+8);
url = 'https://drive.google.com/uc?export=download&id=' + DocID;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
var token = xhr.responseText.match("/confirm=([0-9A-Za-z]+)&/");
window.location.replace(url + '&confirm=' + token[1]);
// should I add url += '&confirm=' + token[1] here instead of window.location?
}
}
};
xhr.open("GET", url);
xhr.send();
}
return url;
}
console.log(fixGoogleDriveURL('https://drive.google.com/open?id=1C25uoL6nIqqNhex3wm8VwODsO2q2pXBt') + "\n<-- should output:\nhttps://drive.google.com/uc?export=download&id=1C25uoL6nIqqNhex3wm8VwODsO2q2pXBt&confirm=XXXXX");
Scraping GDrive using Client-Side JavaScript isn't explicitly allowed by Google and therefore your Ajax call/XHR fails.
The only way to get around that restriction is by using a proxy in the middle that will forward Google's Website code but add appropriate Access-Control Allow-Origin Headers.
You can either use your own server for that (some minimal server-side script code will do) or you can use a service like http://multiverso.me/AllOrigins/ or https://corsproxy.github.io/ to proxy the request for you.
The AllOrigins site has some example code for use with jQuery, but basically they work by URI encoding the URL you want to access and appending that string to the site's proxy URL.
Here's an article by freecodecamp.org that outlines how to use these services (skip to the Don’t Let CORS Stop You! section.
Note: A security advice: These services are working fine right now, but they could go out of business tomorrow and start serving malicious data instead or redirect your file requests to completely different files or completely different websites altogether. It's up to you to decide if you want to trust these strangers or not.

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

Categories

Resources