Load content of file with AJAX (plain JS)

I’m learning JavaScript, so I’m very beginner.
I’m taking an online course, and they show an example code that loads some text from a local text file using AJAX, but it does not work.

This is the code:

<!DOCTYPE html>
<html>
<head>
  <script>
    function loadXMLDoc() {
      var xmlhttp;
      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();  
      }
      else {
        // code for IE6, IE5  
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        //alert (xmlhttp.status);
        if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
          document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
      xmlhttp.open("GET","ajax.txt",true);
      xmlhttp.send();
    }  
  </script>
</head>
<body>
  <div id="myDiv">
  	<h2>Let AJAX change this text</h2>
  </div>
  <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

xmlhttp.status always returns 0 on onreadystatechange (twice), never 200.
I don’t know what is wrong.
Can you help?
TIA

I discovered that I’m getting an error of: “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at”…

But I’m texting the page locally, I also tried in a web server but I get the same error.

I’ve read that I need to set a header

Access-Control-Allow-Origin: *

but I don’t know where. I tried to set it for the XMLHttpRequest after the open command but it didn’t work.

Slightly off-topic:

I would be very wary of a course that supports IE5 and IE6.

4 Likes

Yes, I think it must be a bit outdated, I guess it might be made like 5 years ago or so.
But at the end of the course the site issues a certificate, and as I said I’m a beginner (in JavaScript, although I’ve been programming in a desktop language for many years) so I think it can serve for the purpose to learn my first steps in JavaScript.

1 Like

Hi @JEB, the ajax.txt file your loading would certainly have the same origin as the URL is given as a relative path; you’ll also get a CORS error though when you’re just opening the HTML file from the file system. But if you also tried it on an actual web server that error would be caused by something else…

PS: What’s the actual request URL from that error message? You might also check the network monitor of your browser dev tools (somewhere next to the console) for more detailed information…

I’m testing in locally now, and I’m doing with FireFox.
I get one error message when the page loads, it is:

Then, when I press the button I get this other message:

It has a link “learn more” to a web page that now that I’ve read it more caresfully, it says that for security reasons it does not work with local files.
here is the link: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp
I guess I should be able to configure FF to allow that (still not tried).

When I test it on the web server, just loading the page I first get a warning that says:

I also get the other message related to character encoding missing that I suppose it has nothing to do.

And when I click the button I get two more error messages:

1:

With a link to https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin
and 2:

with a link to https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed

I first supposed there would be something wrong in the code, but now I see that they seem to be that for local files FF doesn’t allow and about my we server I’m not not sure if my hosting doesn’t allow on site request or what, or it needs some configuration.
I use Hostinger for the hosting, and it is a bit limited (to say something).

PS: sorry that I have to remove the links, but being a new user the forum doesn’t allow me to put so many links.

This has nothing to do with the AJAX issue but can easily be fixed by adding for instance

<meta charset="UTF-8">

to the <head> of your HTML document.

Yes as I suspected; but rather than trying to get your browser allow this, you’d usually just start a local dev server to test your web page. For instance, if you have PHP installed on your system, go to the project directory and run

php -S localhost:8080

Then you can open http://localhost:8080/index.html (or whatever the HTML file is called) in your browser. Personally I’m using the live server vscode plugin for quick testing purposes – you can start the server and immediately open the file in the browser with just one click.

This is indeed related to something else (namely GTM).

Just to clarify, did you upload both the HTML file and ajax.txt to that server, or are you still opening the HTML from the file system? The latter won’t work, you have to open it from where you are also serving the requested ajax.txt file.

Thanks.

Yes, sure, done.

OK, I’ll see to install some basic local server to use for testing (I still don’t have installed anything related to PHP, I still didn’t take a PHP course).

That’s very weird, because I don’t have any other code on the page besides what I posted here.
Other pages of the domain have Google Analytics, but I understand that the FF console only shows errors of the current page (I guess)…

Yes, both files are uploaded.

No, I open it from the site URL.

I had several problems with Hostinger hosting in the past, I would not be surprised that it is another annoyance.

Well, no need to install PHP anyway… aforementioned vscode plugin is really nice, or here’s a chrome app that you also gets you going easily:

Hm yes that’s weird… it would be possible that it’s getting injected by your hosting provider, but I’d have to see the page to tell for sure.

Yeah, same… do you have a link to check?

It does not appear any more now. I don’t know what I did before (it does appear for the other pages of the site that has Google Analytics).

http://www.balkesoft.com/test/

Ah, thanks for the link! Now that’s http but there’s an upgrade-insecure-requests policy present, so the request is sent as https and hence the CORS violation. Just open the page over https and it works:

https://www.balkesoft.com/test/

BTW there’s no use in setting a "Access-Control-Allow-Origin: *" header in the request, that’s for the server to decide.

Thank you. I didn’t realize that I was using http.

Still, this is only an exercise, but in an real case, I think that that should be allowed so I think that the " Access-Control-Allow-Origin" should be configured somewhere (I guess from the control panel of the hosting perhaps).

Thank you.

No worries.

ITRW you’d probably just redirect to https though, so that the user visits the site securely in the first place.

Huh why it’s still quoted correctly… if you want to reassign your posts please consult the @admins, not sure if this is possible though.

I have set the automatic redirection to the secured version in the hosting control panel, but for some reason I don’t know why it does not work or doesn’t work always.

Edit: it seems to work when a link is clicked inside the site, but not when the URL is typed in the browser address bar.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.