Search code examples
javascriptajaxrequestcodepen

Why would my AJAX request not work in Codepen.io?


I wasn’t able to make my AJAX request work for the first d3.js FreeCodeCamp project so far, so I decided to test whether if I copy some assignment that I already solved on FCC platform, replace a link with a full link to FCC (https://www.freecodecamp.org/json/cats.json) for the Cat Photo Finder and test whether the it will do anything once I press ‘get message’ button. However, nothing happens when I press on the corresponding button.

Here is my Codepen project for that: Cat Photo Finder Pen

What am I doing wrong here? Is there anything I would need to change in Codepen settings or import any statements to make it work?

Here my code:

document.addEventListener('DOMContentLoaded', function(){
    document.getElementById('getMessage').onclick = function(){
      const req = new XMLHttpRequest();
      req.open("GET",'https://www.freecodecamp.org/json/cats.json',true);
      req.send();
      req.onload = function(){
        const json = JSON.parse(req.responseText);
        let html = "";
        // Add your code below this line
        json.forEach(function(val) {
          const keys = Object.keys(val);
          html += "<div class = 'cat'>";
          keys.forEach(function(key) {
            html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
          });
          html += "</div><br>";
        });
        // Add your code above this line
        document.getElementsByClassName('message')[0].innerHTML = html;
      };
    };
  });
body {
    text-align: center;
    font-family: "Helvetica", sans-serif;
  }
  h1 {
    font-size: 2em;
    font-weight: bold;
  }
  .box {
    border-radius: 5px;
    background-color: #eee;
    padding: 20px 5px;
  }
  button {
    color: white;
    background-color: #4791d0;
    border-radius: 5px;
    border: 1px solid #4791d0;
    padding: 5px 10px 8px 10px;
  }
  button:hover {
    background-color: #0F5897;
    border: 1px solid #0F5897;
  }
<body>
  <h1>Cat Photo Finder</h1>
<p class="message box">
  The message will go here
</p>
<p>
  <button id="getMessage">
    Get Message
  </button>
</p>
</body>


Solution

  • Access to your XMLHttpRequest has been blocked by CORS policy becasue there is not any Access-Control-Allow-Origin header. Returned resource (your json) should have one. It might be atleast Access-Control-Allow-Origin: * which allows all domains.

    This is not problem of codepen.io website. It's problem of the server where you host your json file. You can try another source. As example I've used wikipedia and tested your code with different source.

    You can read more information about CORS at MDN Web Docs - Cross-Origin Resource Sharing (CORS).