3

I am facing an annoying cross origin issue with a very basic jQuery coding. I am trying to call/load a locally placed test-1.html file from my main javascript file.

$('.load-container').load('test-1.html', function(data) {
    $('.load-container').html(data);
});

I want to populate the contents of test-1.html in a div with class load-container.

I am receiving an error in console which states:

XMLHttpRequest cannot load file:--file path--. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

I'm wondering how can calling a locally placed file cause CORS issue. I appreciate your help in solving this issue.

2 Answers 2

4

As mentioned before, this is happening because you are just opening your HTML instead of serving it from a web server.

This is easy to fix using python. Navigate to the directory where your index.html file is and do:

python -m SimpleHTTPServer 1337

Then, you can access your website in: http://localhost:1337

Sign up to request clarification or add additional context in comments.

2 Comments

python3 -m http.server 1337 for Python 3 and above
Does the port have to be 1337, or can it be anything?
2

This error means that you're making a request to a file:// protocol, which is not allowed for security reasons. You need to run your request on a webserver. If you have no remote server, you can install XAMP or IIS on your local machine. There are plenty of guides available on how to do this.

Also note that your jQuery code does not require a callback function, you can reduce it to just this:

$('.load-container').load('test-1.html');

5 Comments

OK. So can you suggest any alternate solution to make the call 'locally' with jQuery ?
Unfortunately not as you need to use a webserver as I mentioned. This is a security restriction of all browsers. It would be a big flaw if you could get around it.
Ahh. That's sad. Well, thanks Rory for your quick answer. Appreciate it :)
@Ayan For chrome that should do it: chrome-allow-file-access-from-file.com (just for testing purpose of course). On FF, not sure about lastest version but on older one there was no restriction. For IE, i don't know. BUT Rory is correct, better is just to run a local server (WAMP, XAMP, LAMP or whatever)
@ A. Wolff Unfortunately, it didn't really work. I would go ahead with IIS for the time being. Appreciate your help though. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.