0

I am trying to load a text file that is stored on my local machine to a div when a button is clicked

My HTML

    <!DOCTYPE html>
<html>
<head>
    <title>Help</title>

    <script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

    <script type="text/javascript" src="index.js"></script>

</head>
<body>

<button id="magic">Click me</button>

<div class="here"></div>

</body>
</html>

My JavaScript

 $(document).ready(function() {

    $("#magic").click(function(){
        $(".here").load("helloworld.txt");
    });

}); 

My text file

helloworld.txt which says hello world!!!!

The error I am getting in the inspector is :

jquery-3.1.1.min.js:4 XMLHttpRequest cannot load file:///home/justin/Code/test/helloworld.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

heybit
  • 205
  • 2
  • 5
  • 10
  • 2
    You should use a web-server for that – Dekel Dec 24 '16 at 17:56
  • 1
    You can't do ajax unless page is opened from a server and not from `file/open`. Install a localhost server – charlietfl Dec 24 '16 at 17:56
  • @charlietfl ajax is possible at `file:` protocol. – guest271314 Dec 24 '16 at 17:57
  • @guest271314 sure if you change browser security settings but in general that's not a good idea and it is so easy to set up a server – charlietfl Dec 24 '16 at 17:58
  • @charlietfl _"You can't do ajax unless page is opened from a server and not from `file/open`"_ is not accurate as to "can't". The flag is used to test functionality locally at chromium, chrome. _"By default, file:// URIs cannot read other file:// URIs. This is an override for developers who need the old behavior for testing."_ – guest271314 Dec 24 '16 at 17:59
  • Caddyserver.com provides a really easy way to setup a webserver – Toby Allen Dec 24 '16 at 18:10
  • @TobyAllen `php` has a builtin server designed to be used locally. Though OP is not asking how to set up a server; but rather, how to use `XMLHttpRequest` to get a file from local filesystem at `file:` protocol, specifically at chromium, chrome browsers. – guest271314 Dec 24 '16 at 18:15
  • You can't do that . because browser doesn't have access to any part of Client .unless you uploaded this file on server and read it by C# or any other language like that and take it by Ajax call – Saman Hajizade Dec 24 '16 at 18:01

0 Answers0