JavaScript AJAX Basics (retiring) AJAX Concepts A Simple AJAX Example

Christos Tsamis
Christos Tsamis
7,983 Points

has been blocked by CORS policy

Code is right, debuged it and and faced a CORS policy problem.. Any ideas?

Juan Lopez
Juan Lopez
Treehouse Project Reviewer

Any chance on you posting your code?

Juan Lopez
Juan Lopez
Treehouse Project Reviewer

3 backticks

    ```javascript 
    /* Your code here*/
    ```
Christos Tsamis
Christos Tsamis
7,983 Points
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="main.css">
  <title>AJAX with JavaScript</title>
  <script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'sidebar.html');
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      document.getElementById('ajax').innerHTML = xhr.responseText;
    }
  };

  function sendAJAX() {
    xhr.send();
    document.getElementById('load').style.display = 'none';
  }
  </script>
</head>
<body>
  <div class="grid-container centered">
    <div class="grid-100">
      <div class="contained">
        <div class="grid-100">
          <div class="heading">
            <h1>Bring on the AJAX</h1>
          </div>
          <button id="load" onclick="sendAJAX()" class="button">Bring it!</button>
          <ul id="ajax">

          </ul>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

(thanks by the way ^^ )

2 Answers

Reinhard Liess
Reinhard Liess
Full Stack JavaScript Techdegree Student 13,786 Points

My suggestion would be that if you use Visual Studio Code to use the Live Server extension, that should fix your problems.

Christos Tsamis
Christos Tsamis
7,983 Points

i am doing so, i will try that! thanks!

Kevin Lewis
Kevin Lewis
15,087 Points

Worked for me. Thank you!

This is actually a really common frustration for developers and likely has nothing to do with your code: As a security feature, Chrome does not allow "cross-origin resource sharing" when you're working on localhost or just using File>Open to load a webpage locally. There are a few work-arounds, the best of which might be to run a local server with a domain alias -- but I understand that's asking a lot if you've never done it and just want to do this one thing. I personally would not suggest setting any flags --disable-web-security that would compromise your browser. Here's some discussion about it: https://stackoverflow.com/questions/10883211/deadly-cors-when-http-localhost-is-the-origin.

Christos Tsamis
Christos Tsamis
7,983 Points

Eric Butler thank you, i run the project on a local server.... had to change browser to follow up the course.. thank you for your answer!