question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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>

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:15 (8 by maintainers)

github_iconTop GitHub Comments

7reactions
HarplingeTomcommented, Oct 31, 2018

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.

7reactions
RandellDawsoncommented, Aug 28, 2018

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.”

Read more comments on GitHub >

github_iconTop Results From Across the Web

Post Data with the JavaScript XMLHttpRequest Method url not ...
Issue: "ReferenceError: url is not defined" in challenge "Post Data with the JavaScript XMLHttpRequest Method".
Read more >
Uncaught ReferenceError: url is not defined - Stack Overflow
Because you define and populate url in the block of code surrounded by $(function() { }) , that runs when the document is...
Read more >
jest xmlhttprequest is not defined
Node.js - Errors - ReferenceError: XMLHttpRequest is not defined Attempting to run the following JavaScript code (an AJAX call using XMLHttpRequest) throws ...
Read more >
JavaScript Tutorial: The Basics
Basic JavaScript Tutorial for the beginners.
Read more >
Laravel Vite & JQuery - Laracasts
- First your route URL request load - then app.css - then app.js - then all other imports (like fonts, svg, css, js)...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found