Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) Programming AJAX Parsing JSON Data

Why doesn't the onreadystatechange event need a parentheses?

In the video onreadystatechange doesn't have a parentheses after. Why not?

2 Answers

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

Hi there,

The onreadystatechange is a method that your provide on the xhr object. If you used parentheses you're firing it.

Here's an example with the onclick method on a button:

<html>
<body>
      <button>Greeting</button>
      <script>
            var button = document.querySelector("button");
            button.onclick = function() {
                  alert("Hello World");
            }
            button.onclick();
      </script>
</body>
</html>

This will automatically trigger the onclick method and show the alert.

What you're doing by setting the method to onreadystatechange is providing a method for the browser to call when it's ready. The difference between onclick example above is that we were triggering the event, the browser is triggering it in the AJAX example.

Regards
Andrew

onreadystatechange doesn't have parentheses because it doesn't take arguments and doesn't need to. It exists to contain a function that executes automatically when the readyState changes. If you need to pass an argument, you can do it in the parentheses that are part of the function contained in the onreadystatechange value.