I'm currently working on a project where I send AJAX requests, receive responses, and replace text based on those responses. However, it seems like I may be missing a fundamental concept in my approach.
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
let newCard = JSON.parse(request.responseText);
// replace content.
request = new XMLHttpRequest(); // Attempting to reset the request here.
request.open('POST', '/viewed', true);
} else {
console.log('Error ' + request.status + ' text: ' + request.responseText);
}
}
request.open('POST', '/viewed', true);
// $close is an element on the page.
$close.addEventListener('click', function() {
request.send(params);
});
Initially, when I click once, I get the new content. However, on the second click, no new content appears. After the third click, I encounter an AJAX error.
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
I believe that attempting to reset the request
inside the if block is where I am encountering issues. I'm just unsure of the correct method or location to handle this effectively.