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 request on button element

I put an ajax request to run on a HTML button element onClick attribute.

It will run on the first initial click, but anything after the first i get the following error "Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED."

Why does this happen and how do i solve it?

My Code:

let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() { if(xhr.readyState === 4) { if (xhr.status === 200) { let response = JSON.parse(xhr.responseText) console.log(response.title) } } };

xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/2");

1 Answer

Reading the err thrown i just added the xhr.open() to the body of the ajax call back function

That fixed it, but is that a appropriate solution to the error?