JavaScript AJAX Basics (retiring) AJAX Concepts A Simple AJAX Example

Pitrov Secondary
Pitrov Secondary
5,119 Points

I don't know why it's not working

Can u help me with this one, I cant make it to work heres a snapshot https://w.trhou.se/v20iqp4nzt

Sheila Anguiano
Sheila Anguiano
17,766 Points

Hello, I inspected your code with Chrome DevTools and the error is on line 19. It's says you're calling xhr as a function while is a variable.

Pitrov Secondary
Pitrov Secondary
5,119 Points

Sheila, the code doesn't still work, Can u find any other problems?

Sheila Anguiano
Sheila Anguiano
17,766 Points

Hello, I don't know if you solved this problem already, but I'll give it another try. So let's get specific to make the most of our time:

  1. I'm assuming you're using workspaces for this exercise OR your own text editor with a Development server
  2. That the problem you're having is with file index.html lines 8-20 (Please try to give as much information as possible when asking a question, otherwise it makes really difficult for other classmates to help you)

So here is your code from line 8-20:

  <script>
let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if(xhr.readyState === 4) {
        document.getElementById('ajax').innerHTML = xhr.responseText;
      }
    };
    xhr.open('GET', 'sidebar.html');
    function sendAJAX() {
      xhr.send();
}
    document.write(xhr());
  </script>

Let's review it or rubber duck it step by step against the 4 steps in the AJAX process:

  1. Create an XMLHttpRequest Object.
let xhr = new XMLHttpRequest();
  1. Create a callback function
   xhr.onreadystatechange = function () {
      if(xhr.readyState === 4) {
        document.getElementById('ajax').innerHTML = xhr.responseText;
      }
    };
  1. Open a request
    xhr.open('GET', 'sidebar.html');
  1. Send a request Here is the problem, you don't need a function, just need to apply the .send method to your xhr variable, so DELETE this:
function sendAJAX() {
      xhr.send();

and REPLACE IT with just this: xhr.send();

That should work. Also try to complete JavaScript Basics and JavaScripts Loops, Arrays and Objects first before completing AJAX, it makes much more sense after those.

2 Answers

Pitrov Secondary
Pitrov Secondary
5,119 Points

plz guys, help me I cant get any further now

Jared Ledbetter
Jared Ledbetter
16,799 Points

<script> var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { document.getElementById('ajax').innerHTML = xhr.responseText; } }; xhr.open('GET', 'sidebar.html'); xhr.send(); </script>