Steps to correctly reset an XMLHttpRequest object

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.

Answer №1

The purpose behind the xmlhttp request calls is ambiguous. If your intention is to trigger the request on click, consider setting an event listener on a specific element for the request initiation.

Answer №2

Big shoutout to Sam Onela and squint for their helpful pointers that guided me in the right direction. Specifically, I found it crucial to establish a handler for the new XMLHttpRequestObject. The link they shared provided me with the essential framework:

function updateCard() {
  let request = new XMLHttpRequest();
  request.onreadystatechange = () => {
  if (request.readyState === 4 && request.status === 200) {
      let newCard = JSON.parse(request.responseText);
      // updating element
     } else {
       console.log('Error ' + request.status + ' text: ' + request.responseText);
     }
  }
  request.open('POST', '/viewed', true);
  request.send(params);
}

$close.addEventListener('click', function() {
  updateCard();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

The most recent release of Chrome (Version 47.0.2526.80 m) introduces an intriguing feature. When using navigator.webkitGetUserMedia, the returned stream now lacks a

I recently encountered a problem with my code that used to access the camera on Chrome browser and release it after use. Here's the code snippet: Starting the Camera: navigator.webkitGetUserMedia($scope.options.videoObj, function (stream) { $sco ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...

JavaScript can extract a portion of an array

Is it possible to generate a new array consisting of all elements ranging from the nth to the (n+k)th positions within an existing array? ...

Dot/Bracket Notation: flexible key assignments

I have an item that contains various image URLs accessed through data[index].gallery.first.mobile/tablet/desktop "gallery": { "first": { "mobile": "./assets/product-xx99-mark-two-headphones/mobile/image-gallery-1.j ...

Sending a json array from PHP

I spent several hours searching for solutions to my problem but couldn't find an answer. I'm trying to perform a search on the same page using jQuery, AJAX, and PHP. Unfortunately, the array from PHP is still returning undefined. Here is the P ...

Refreshing events in FullCalendar 5 using Vue.js's refetchEvents

I am currently integrating FullCalendar with Vue.js. My goal is to reload the events when the refreshCal() function is triggered, thereby rendering the calendar on the screen using refetchEvents. I have two main components: The Calendar: here is the code ...

Use the Nodejs HTTP.get() function to include a custom user agent

I am currently developing an API that involves making GET requests to the musicBrainz API using node.js and express. Unfortunately, my requests are being denied due to the absence of a User-Agent header, as stated in their guidelines: This is the code sn ...

Retaining original input value even when validation is applied with input type="number"

Encountering an unusual scenario while using angularJs and input type="number". It seems that if the initial value of an input falls outside the specified min and max range, the value gets wiped out. To better visualize the issue, I created a fiddle - htt ...

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

What is the method to retrieve the color of a linearGradient in an SVG at a particular

I am working on a unique progress bar that uses a linear gradient and a small ellipse to indicate the completion percentage. The AngularJS binding updates the completion percentage and a function is called. My challenge is to change the color of the ellip ...

Calculate the total width of all images

I'm on a mission to calculate the total width of all images. Despite my attempts to store image widths in an array for easy summing, I seem to be facing some challenges. It feels like there's a straightforward solution waiting to be discovered - ...

Vuetify's data table now displays the previous and next page buttons on the left side if the items-per-page option is hidden

I need help hiding the items-per-page choices in a table without affecting the next/previous functionality. To achieve this, I've set the following props: :footer-props="{ 'items-per-page-options':[10], &apo ...

Tips for validating a dynamically created form with Bootstrap tabs using jQuery

For my project, I am dynamically creating an HTML form using jQuery. The page consists of five tabs, each with separate previous and next buttons. These tabs are designed using Bootstrap. Can someone please suggest the easiest way to validate this page? Fo ...

ng-model in html input with a name of "foo[]"

Apologies for the lack of a more specific title. In HTML, when we need multiple values for a given name, we utilize the name="foo[]" attribute. Upon posting the data, it arrives as an array. I am seeking this same functionality with ng-model in Angular. ...

Is there a way for me to convert this JSON object back into a string?

Presently, I possess this specific JSON object "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "homeworld": "Tatooine", "films": [ "A N ...

Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tri ...

Changing Image Size in Real Time

Trying to figure out the best way to handle this situation - I need to call a static image from an API server that requires height and width parameters for generating the image size. My website is CSS dynamic, adapting to different screen sizes including ...