jQuery .load() with Relative Path - XMLHttpRequest Cannot Load - Workaround? - javascript

I have a locally-stored project whose directory structure is the following (I minimized non-relevant folders):
What I want to do is that in an HTML file, like index.html, to add a <header> such that its contents would be loaded from an external HTML file, so all of what I'll have to write in index.html would be <header>, and my solution would load the content automatically.
To do this, I'd like to use JavaScript (preferably jQuery, but I'll accept other solutions if they work and jQuery doesn't, or if they work and executed faster than jQuery).
I don't think that I should use an <iframe> due to the fact that it'd probably increase loading times more than using jQuery/JavaScript (which, like I said, is what works now, when the website is live).
Right now, I'm using the jQuery .load() function. I don't know much about jQuery, but I've been told that it should work locally - and it doesn't, for me.
My browser's console shows me the problem:
jquery-3.1.1.min.js:4 XMLHttpRequest cannot load file:///C:/Users/GalGr/Desktop/eiomw/header.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
And I'm trying to overcome it.
This code works on my live website - it might not be updated to the code of the files that I linked to below, but it doesn't matter - their code matters.
This is the index.html file:
index.html
This is the header.html file:
header.html
This is `main_script.js:
main_script

The reason you're having a problem with this locally is mainly down to security measures in your browser.
Essentially whenever you're using jQuery's load() function it makes a separate HTTP request (approach known as AJAX) for the file or URL you give it.
Modern browsers enforce that the URL you request using AJAX methods is from the same origin (server) as a security feature to stop pages randomly loading content from anywhere on the internet in the background. In your case it seems like this shouldn't affect you because you're browsing your pages locally and the request you're making using load() is also for a local file (header.html).
However, I am assuming you're just opening up the page directly in your browser, so your browser's URL will look something like 'file:///C:/Users...' (similar example in the error message you gave). This means your browser is directly reading the file from disk and interpreting it as HTML to display the page. It seems likely you don't actually have a local HTTP server hosting the page, otherwise the URL would start with 'http://'. It is for this reason that the browser is giving the security error, even though your AJAX request for header.html is technically from the same source as the page it is executed on.
Your server will have an HTTP server which it's using to host the pages, and so everything works fine as you're then using HTTP as normal, and this security feature does not get in your way.
I would suggest that you simply install an HTTP server locally on your dev machine. You don't even need to 'install' one per-se, there are loads of development HTTP servers that just run standalone, so you start them up when you want to browse your local HTML files. As you appear to be on Windows, I'd check out either IIS (Windows' HTTP server) or IIS Express (like IIS but runs standalone). There are also many others available like Apache, Nginx, etc. etc.
If you do this, you can host your pages on something like 'http://localhost/index.html'. Then, any AJAX requests you make for local files will work fine, just like your server.
Hope that makes sense, and I'm not telling you something you already know?

Why not using something more straight foreword like mustache.js ?

I found a solution:
Using phpStorm's built-in localhost, I was able to emulate a server that handles my requests and responses.

Related

AJAX Load on the client side workaround | Cross Origin requests error

I am aiming to create a visual novel, "click" progression game. I am aiming to achieve that using purely HTML, CSS and JS. The game is supposed to run only on the client side from index.html in the browser.
My question is, I am hitting up some trouble with those cross origin requests and I'm trying to figure out a solution from 2 weeks now, and i have no idea how to make this happen. Error "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
What i want to achieve is very simple. Instead of using something like twine engine, i would like to write native, because it will be more productive and faster for me.
Options i tried so far:
JQuery Load - requires server
Wrote a pure XML Ajax load - CORS error. (so... server)
I started to write html into js files and load them instead, then use document.write or innerHTML to replace, but that can only get me so far and its hard to extend after 5 files.
What can i do to get this running? I know C#, but before i move to .exe is there anyway i can get this done? Will react.js work client side only and load components without CORS error? Never tried the framework, because in the tutorials i see they use a webserver.
Any ideas? Thanks beforehand!
Will react.js work client side only and load components without CORS error?
No, because it will still be another thing that runs in the browser and is subject to the limitations imposed by the browser.
You need a server, a browser which doesn't impose those limitations, (something that sort of combines the two like Electron), to use a dirty hack like JSONP to load the files, or to wrap up all the files so they are embedded in the JS you load initially.

AJAX Request Won't Work on Internal Server

I'm using w3schools to try to understand how simple AJAX requests work and I came across this exercise page:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_load
I thought it was a simple example of an ajax request, so I copied and pasted the code into a plain ajax.htm file and copied and pasted the txt file it refers to:
http://www.w3schools.com/jquery/demo_test.txt
...and saved it as demo_test.txt file it refers to and saved them both in the same folder. (Keep in mind, I have an Apache server that processes PHP locally with no problem, so I would think a simple request like this would work on my local machine).
However when I click the button locally I get nothing. Then, when I upload the files to a different server (a "web host") suddenly it works.
So, this works on a webhost and it works at w3schools but it doesn't work locally on my machine in my root folder (where php works without a problem).
I would prefer to not have to upload my code before being able to test whether it works and would rather be able to process everything locally, like I do with PHP. Is it possible to do this locally or can I only make these requests remotely from my web host?
Why is my machine not processing this code? Any help would be appreciated. Thanks.
There are a lot of reasons you might not be able to load the file locally, but most will have to do with how you're serving the files. If you're using file:// you're going to run into problems; you said you have an Apache server, but didn't mention whether you were actually serving this site from it.
Have you checked to make sure that the route you're loading via your AJAX call is actually loading properly? E.g. if the ajax file is at your web root (http://local.site/ajax.html) and so is your txt file (http://local.site/demo_test.txt).
In this situation you can also always check your browser's Javascript console to see if you get any errors or if the files are actually loaded correctly. Depending on how you're serving and accessing the various files, you might be getting CORS errors as well.
The simplest solution is to make sure you're running on a local webserver (your Apache) instead of directly viewing files.

Javascript used to include html, is it cached?

I'm using a method of creating a .js file on server #1 which contains document.writes to write html code, then a simple js include inside html code on server #2 to load that html code (there are multiple server #2's). This is basically replacing an iframe method with the advantage being that each server #2 owner controls their own css.
The method works perfectly as is. My question has to deal with caching. Each time the page is loaded on server #2 I want the .js reloaded, as it will change frequently on server #1. This appears to be the case on each browser I tested, but can I rely on this as being the default case, or is it dependent on browser settings? Despite all I've read on caching I can't figure out what triggers the load for a case like this.
You can control browser caching using HTTP headers on the server side. Like cache-control and cache-expiration. More here - http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
In a case like this, the caching is triggered by the cache policy of the js file. Not the html file.
The browser doesn't cache the rendered page (well, it does for back buttons but that's not what we're talking about). The browser caches the source file. Therefore even if the html page is configured to be cached for a long time the javascript injected content will only be cached as long as its been configured to.
To configure caching policy you need to set specific headers on the server side. Sometimes you can do this in a CGI script. Sometimes you can do this in the server configuration files.
Google "http caching" and read up on how to configure a page to be cached or not cached (also google "json disable caching" or "ajax disable caching" because this issue crops up a lot with ajax).

Tips for locally debugging web pages that contain protocol relative URLs

There is probably a better title for I'd like to accomplish, but the details should be helpful.
I've recently learned that specifying a script's src path as //some.domain.com rather than http://some.domain.com or https://some.domain.com will cause the browser to request the script using whichever protocol was used to load the page. This works great when the page is loaded from a site, but often I debug on my local system, so the protocol is file, and of course errors occur whenever resources or scripts aren't found.
Other than changing src paths, is there a better way to debug locally? I imagine there is code solution that detects when the page is running locally versus loaded from a domain, but I haven't found examples yet.
Install a product such as wampserver, then you'll have a localhost webserver you can test everything on. This is how I do it, works like a charm.
There are similar products available for ASP or other non-PHP server-side technologies (you didn't specify), if you are just doing HTML + JS then any old server would do.

Double-Click HTML files and JQuery

I noticed that when I open HTML file locally by double clicking on it, it will not "run" the same as if I had it on a web server and opened it by HTTP GET request.
I need to have a local HTML file a user can open by double clicking on it. This HTML file has several JQuery load calls such as this:
$("#content").load("http://somepage.com/index.html");
I want to update several divs with content from remote sites.
This works fine If I have this file on a web server but not if I double click it under windows explorer... How can I "make" the file "run" as it would on a web server?
I think you pretty much cannot. This has to do with domain-access restrictions, which are there to avoid cross site scripting and the likes.
The files on your hard drive are especially limited - think what the life could be if they were allowed to treat your whole hard-drive as a single domain.
If you want things to work properly you need to be running a server. XAMPP is a pretty good bet as it's easy to install and set up.
Any non-AJAX javascript will work fine as is though, as long as the paths to include any css or js are relative.
You can't do this locally. You have to have it hosted somewhere for this to work. It's done this way for the sake of security.
What are you trying to do that you "need" to have this?

Categories