Code issue in JavaScript


the code is not working why …


and also when i search it in google the answer is not similar
as it is shown in the video … i mean about the web api …

Hi @rishabhgarai33,

There are a couple of issues in your HTML and JavaScript code. I’ve corrected them below:

<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  <p id="output">default text</p>
  <input id="user_number">
  <button onclick="update_users()">Submit</button>

  <script type="text/javascript">
    function update_users() {
      var user_number = document.getElementById("user_number").value;
      var httpRequest = new XMLHttpRequest();
      httpRequest.open("GET", "https://reqres.in/api/users/" + user_number);
      httpRequest.send();
      httpRequest.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          var user_data = JSON.parse(this.responseText);
          document.getElementById("output").innerHTML = user_data.data.first_name;
        }
      }
    }
  </script>
</body>

</html>

Changes made:

  1. Corrected the typo in document.getElementbyId to document.getElementById.
  2. Changed onradystatechange to onreadystatechange.
  3. Moved the update_users function call to the button’s onclick attribute.
  4. Updated the API URL to “https://reqres.in/api/users/” to match the correct endpoint.

Make sure to test it with valid user numbers. Additionally, check for any browser console errors for debugging purposes.

There are some errors in this code.

  1. It should be instead of
  2. In the function update_users(), it should be document.getElementById(“user_number”) instead of document.getElementbyId(“…”)
  3. In the httpRequest.open() line, the URL should be “https://reqres.in/api/users” and not “https://reqres.in/api/user
  4. It should be httpRequest.onreadystatechange and not httpRequest.onradystatechange
  5. Finally, the last line of code must be document.getElementById(“output”) and not document.getElementbyId(“output”)

These are common mistakes that everyone makes. My advice is to always confirm whether these mistakes have been commited or not before debugging your code. It forms a good coding ethic and also helps your mental well-being.