Preserve and recover the dynamic form value following an AJAX update

Looking for a solution for saving and restoring user comments on dynamically created form fields in a page where users can comment on posts. How can we save and restore the typed comments before an ajax refreshes the div holding all the post and comments?

Attempted to implement the following code without success:

<textarea id="comment_field" onKeyUp="return saveAndRestoreTypedStrings(this)"></textarea>

or  

<textarea id="comment_field" onchange="saveAndRestoreTypedStrings(' + id + ');"></textarea>

The function used is as below:

function saveAndRestoreTypedStrings(id){
   document.getElementById("post_comment").onchange = function() {
     localStorage['post_comment'] = document.getElementById(id).value;
    }
    window.onload= function(){
        if(localStorage['post_comment'])
            document.getElementById(id).value = localStorage['post_comment'];
    }   
}

In order to distinguish the form a user is working on, a unique id has to be passed to the saveAndRestoreTypedStrings(id) function.

This issue occurs when ajax refreshes the div containing the posts and comments every 3 seconds. If a user is typing a comment and the div reloads, the typed content is lost. Would appreciate any suggestions or ideas on how to tackle this problem.

Answer №1

The window.onload event triggers when the webpage has finished loading completely, so I don't believe it would be relevant in your situation.

Have you considered utilizing a callback function after the AJAX operation is done? This way, you can "restore" the information by accessing localStorage.

Just a heads up, I am unable to leave comments at the moment.

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

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

The onbeforeunload event should not be triggered when the page is refreshed using a clicked button

Incorporated into my webpage is a sign-up form. I would like it to function in a way that if the user accidentally refreshes, closes the tab, or shuts down the browser after entering information, a specific message will appear. <input type="text" place ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Setting up your NODEJS Express Server to handle POST requests: A Step-by-Step Guide

I am currently developing a quiz app that utilizes the Gemini API to generate questions. The frontend of the app is built using HTML, CSS, and Vanilla JavaScript, while the backend is powered by Node.JS with Express. Every time I make a fetch request usin ...

Is it possible to identify when someone is copying a URL in a web browser?

During a recent conversation with a taxi driver, I mentioned that I work as a programmer. He then proceeded to tell me about an unusual experience he had a few days ago. While trying to copy the URL from his browser's address bar, a message box popped ...

Is it possible to drag the parent element but only select the text within the child

How can I make the parent div draggable, yet keep the text in the child span selectable? <aside draggable="true" id="dragme"> This is an aside, drag me. <span id="copyme" draggable="false">But copy me!</span> </aside> A simila ...

Strategies for combining objects with varying structures on a map

SUMMARY: Looking to merge the data from Students into the corresponding values of Employees, where the value from Students should be included in the same array as Employees['avg_rate' and 'expense']. The updated object array should be ...

What is the best way to show only one div at a time when selecting from navbar buttons?

To only display the appropriate div when clicking a button on the left navbar and hide all others, you can use this code: For example: If "Profile" is clicked in the left navbar, the My Profile Form div will be displayed (and all others will remain hidde ...

designing a corner tab element

I'm aiming to create a triangular button in the upper-right corner of my website using fixed positioning. It will be an icon on top of a background color with a hover effect. I'm curious if it's possible to achieve this with an angled div or ...

Unable to access MongoDB API via standard HTTP requests

I've been attempting to access the MongoDB API using an API key for authentication, but I keep receiving a 401 status code. Below is the code snippet I've been using: fetch(‘https://eu-west-2.aws.data.mongodb-api.com/app/application-0-dhdvm/en ...

Ways to determine the presence of a value in an array using AngularJs

I'm currently working on looping through an array to verify the existence of email, phone, and alternate phone in a database. My challenge lies in finding a suitable function or workaround in AngularJS that allows me to iterate through the array with ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

Prevent identical values from being added repeatedly to a table while updating in real-time

Currently, I am facing an issue while running through a loop to extract values from an array. When I add a second value, it duplicates both the new and previous values in the table. For example, adding a row with value 488 works fine: <tr class="exe"& ...

Tips for displaying a digital keyboard when a webpage loads on iOS Safari

While developing a website, I noticed that the virtual keyboard fails to appear when an input field gains focus during the page load process. As per Apple's policy restrictions, this functionality is not allowed. However, I am interested in finding a ...

Tips for utilizing the value obtained from an AJAX URL in Yii

Recently I started using Yii and I have a form with a combo box and a text field. What I want to achieve is changing the value of the text field based on the selection made in the combo box. I am able to get an AJAX url by changing the combo box value, and ...

What is the best way to retrieve the request object within a Mongoose pre hook?

Is there a way to have the merchantID in documents automatically set to the logged-in user found in req.user when saving them? product.model.js: const ProductSchema = new Schema({ merchantId: { type: ObjectId, ref: "Merchant", requ ...

Switching the background color of a button on click and resetting the color of any previously clicked buttons (a total of 8

I'm struggling to implement a feature where only one button out of a column of 8 should be toggled yellow at a time, while the rest remain default green. Unfortunately, I can't seem to get the function to execute on click, as none of the colors a ...

Unexpected response: The JQuery AJAX request did not return the expected JSON data

Within my code snippet below, I have successfully obtained an object that, when printed to the console, begins with: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ,  …} However, up ...

Is there a way to display a modal newsletter popup just one time during a user's session?

I am trying to implement a modal popup that only shows once per session, but I am facing an issue where the div pops up every time I visit the homepage. My attempt to use cookies to fix this problem has not been successful. <script> if (!Cooki ...