1

I want to load content of external text file (demo.txt) in my div on button click.

Text file containes text 'Demo text.'

But it shows error

XMLHttpRequest cannot load file:///C:/Users/Tom/Desktop/jQuery%20thenewboston/76.)%20Load%20function/demo.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

on my browser console.

$(document).ready(function(){
 $('#button_file').on('click',function(){
  $('#load_html').load('demo.txt');
 });
});
<button type="button" id="button_file">Load file</button>
  <br />
     <div id="load_html" >
  </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I am a beginner in jquery , please comment below for any query.

R K
  • 307
  • 7
  • 22

4 Answers4

2

You cannot get the result because the remote site doesn't have CORS enabled: If you look at the console, you'll see:

(Reason: CORS header 'Access-Control-Allow-Origin' missing).


You can bypass CORS by using something like anyorigin.com, i.e.:

$.getJSON('http://anyorigin.com/get/?url=http%3A//thenewboston....&callback=?', function(data){
    $('#div-data').html(data.contents);
});

PS: If it's a local file, make sure you load it on the same address as the script, (localhost, 127.0.0.1, 192.168.1.1, etc...)

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

You are being restricted by HTTP access control (CORS). The file you are requesting asynchronously needs to be from the same domain or the domain you are accessing it from needs to allow your domain to access it. As you are using the file:/// protocol you need to allow it, so check out this if that's the way you wish to go.

Alternatively you can create a local web server to host your site an allow access to the file on the same domain.

Community
  • 1
  • 1
Clarice Bouwer
  • 3,631
  • 3
  • 32
  • 55
1

In order to make this work you need to use a web server instead of using just clicking on the html file.

Check XAMPP

0

Unfortunately, Google Chrome doesn't allow cross-origin request although Firefox does.

Alternatively, if the text file is short you can store it in an object and place it wherever you like.

    text_file = {
          contents = 'content';
    }

    $('.button_class').on('click',function(){
         $('.div').html(text_file.contents);
    });

I would never suggest you use this but if it's a small project, a one page application that nobody will see the code to - desperate times call for desperate measures.

The best thing to do is to use XAMPP and PHP. Load in from your database the content you would like to show. You can read the PHP documentation or watch online tutorials , I personally suggest TheNewBoston PHP Tutorials with Alex Garrett