Freecodecamp: "ReferenceError: url is not defined" in challenge "Post Data with the JavaScript XMLHttpRequest Method"

Created on 19 Mar 2017  Â·  15Comments  Â·  Source: freeCodeCamp/freeCodeCamp

Challenge post-data-with-the-javascript-xmlhttprequest-method has an issue.
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36.

The code below actually yields a ReferenceError: url is not defined on the console. Yet, all tests are passing. Where is the variable url supposed to come from? Apologies, if this is work in progress, but I thought I'd point it out. Feel free to rope me in for fixing this—dev environment is all set up 😀



<script>
  document.addEventListener('DOMContentLoaded',function(){
    document.getElementById('sendMessage').onclick=function(){
      var userName=document.getElementById('name').value;
      // Add your code below this line
      req=new XMLHttpRequest();
      try {
        req.open("POST",url,true);
      }
      catch (e) {
        console.log(e);
      }
      req.setRequestHeader('Content-Type','text/plain');
      req.onreadystatechange=function(){
        if(req.readyState==4 && req.status==200){
          document.getElementsByClassName('message')[0].innerHTML=req.responseText;
        }
      };
      req.send(userName);

      // Add your code above this line
    };
  });
</script>
<style>
  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;
  }
</style>
<h1>Cat Friends</h1> 
<p class="message box">
  Reply from Server will be here
</p>
<p>
  <label for="name">Your name:
    <input type="text" id="name"/>
  </label>
  <button id="sendMessage">
    Send Message
  </button>
</p>

help wanted learn

Most helpful comment

The following code fixes this I think. I don't think the people at jsonplaceholder.com will mind, it's their reason to be after all.

<script>
  document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('sendMessage').onclick = function() {
      var userName=document.getElementById('name').value;

      // Add your code below this line

      const url = 'https://jsonplaceholder.typicode.com/posts';
      const messageBoard = document.getElementsByClassName('message')[0];

      const xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 201) {
          const serverResponse = JSON.parse(xhr.response);
          messageBoard.textContent = `${serverResponse.userName} ${serverResponse.suffix}`;
        }
      }
      const body = JSON.stringify({ userName: userName, suffix: " loves cats!" });
      xhr.send(body);

      // Add your code above this line
    };
  });
</script>

Note the use of .textContent instead of .innerHTML, a better practice when you can use it.
Also checking for HTTP status of 201 instead of 200. Probably endpoint dependent but when you are POSTing there's a good chance you'll be creating a resource on the server and as is the case with jsonplaceholder you'll get something other than 200 back.

All 15 comments

I believe the aim of this challenge is not to produce code that actually works but to verify you're calling the right methods.

If you had a server set up that could accept a POST request to, say, /cat-lover, then you would replace url with that URL and your code would be valid and working.

Sure, I do get that. I just don't think it suits FCC to let students get away with syntactically false code that wouldn't work unless inside a try-catch block.
Imho, it would be better to put a note there, explaining that url is not a real API endpoint for a POST or provide a real endpoint.

I mean… putting your name inside the input field and pressing the button doesn't do anything. I can see people getting confused.

@stephanmax I agree with you.

Could you come up with a terse single-sentence explanation like "Note that this is a learning exercise and this wouldn't normally work without additional server-side code" or something like that and add it to the challenge?

Will do, @QuincyLarson

Can this be reopened, because it was never changed? The instructions need to be updated, because currently, the instructions state:

Update the code to create and send a "POST" request. Then enter your name in input box and click "Send Message". Your AJAX function will replace "Reply from Server will be here." with the reply of the server. In this case, it is your name appended with " loves cats".

On the forum we are getting people wondering why when they type in their name (i.e. "John") and click the Send Message button, that the "Reply from Server will be here." message is not replaced with "John loves cats."

I would like to propose just removing this entirely. This is a data visualization series after all and devoting a lesson to this POST request is probably not contributing much. Probably this whole section should give more support to the skills necessary to complete the following projects. If each of these lessons utilized an AJAX request that would be good, but it would be better if each also added some new aspect of data visualization.

I get that data visualizers are likely to be making AJAX requests and parsing JSON, but make that just what you do to get the data in each of these lessons and focus on data visualization.

The following code fixes this I think. I don't think the people at jsonplaceholder.com will mind, it's their reason to be after all.

<script>
  document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('sendMessage').onclick = function() {
      var userName=document.getElementById('name').value;

      // Add your code below this line

      const url = 'https://jsonplaceholder.typicode.com/posts';
      const messageBoard = document.getElementsByClassName('message')[0];

      const xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 201) {
          const serverResponse = JSON.parse(xhr.response);
          messageBoard.textContent = `${serverResponse.userName} ${serverResponse.suffix}`;
        }
      }
      const body = JSON.stringify({ userName: userName, suffix: " loves cats!" });
      xhr.send(body);

      // Add your code above this line
    };
  });
</script>

Note the use of .textContent instead of .innerHTML, a better practice when you can use it.
Also checking for HTTP status of 201 instead of 200. Probably endpoint dependent but when you are POSTing there's a good chance you'll be creating a resource on the server and as is the case with jsonplaceholder you'll get something other than 200 back.

@HarplingeTom Thanks for your patience. I agree with your assessment. I've reopened this issue. Would you be interested in going in and updating the challenge to make use of this?

Hi Quincy! Sure I would be happy to make a contribution. The only thing is that I'm a bit of a noob, so while I could write the code I don't really know how to incorporate it into your ecosystem. Do you think if I looked around the site that I would find all the info I need to do it properly?

@HarplingeTom You could certainly try. We have a lot of contributing documentation, and we're always around in gitter.im/freecodecamp/contributors if you have questions or get stuck.

How is this coming @HarplingeTom? Were you able to get the repo setup locally? Do you still want to try and tackle this?

I felt free to fix this issue (tagged as _help wanted_). I follow the recommendations of @HarplingeTom . The PR is #35415

I felt free to fix this issue (tagged as _help wanted_). I follow the recommendations of @HarplingeTom . The PR is #35415

is it released?

why don't you change the instrucctions to specify the url which to send the post request?? how do you explain to the new students where this url variable is coming from?? wouldn't be better that way??

@arnaldoperez url is set. Did you read #35415 ?

Any update on this? lesson passes but message still not getting replaced.

Was this page helpful?
0 / 5 - 0 ratings