Post Data with the JavaScript XMLHttpRequest Method can some one help me fix my code?

My code

<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();

req.open("POST",url,true);

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>

link to challenge: https://www.freecodecamp.org/learn/data-visualization/json-apis-and-ajax/post-data-with-the-javascript-xmlhttprequest-method
Anyone have any idea how to fix this?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

req is not defined, you may need to define it before using it, with a certain keyword

the variable url is not defined, you may need to reset the challenge

you get the errors in the console if you write something in the input box and use the “Send message” button

This challenge is a bit strange, you can literally just copy-paste the example code. Also, I don’t really see how a camper would be able to do this purely with the information given in the challenge. It seems like you are just supposed to copy-paste the code.

I updated the hint page with the solution and some hints, or at least I tried. It’s pretty much just a rundown of the example code.

to be honest, all that section is just copying and pasting the examples

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