简体   繁体   中英

Regularly send POST request when user changes value in <textarea>

I created a form in which user puts some food names to the menu in textarea and then he/she can press button to submit this form and send a POST request. After submitting, all data from textareas (there are 20 of them) is being sent to mongoDB. It works absolutely fine. The problem is: it takes time for user to fill all 20 textareas, so i wanted to make some kind of "autosave", just in case browser stops working or other errors occur and to prevent data loss. Data must be sent to database every time changes occur in the textarea. How is it possible to send POST request from form without clicking submit button and just by changing value of textarea.

 <form method="POST" action="/"> <table> <caption style="margin-bottom: 20px; font-size: 2em"><b>MENÜÜ</b></caption> <tr> <td style="column-span: 2; border: none; font-size: 0.8em">ESMASPÄEV</td> </tr> <tr> <td class="hommikusook">Hoomikusöök</td> <td class="userinput"><textarea name="MondayBreakfast" class="textarea" placeholder="Kirjuta siia" autofocus></textarea></td> </tr> <tr> <td class="vitamiiniamps">Vitamiiniamps</td> <td class="userinput"><textarea name="MondayVitamin" class="textarea" placeholder="Kirjuta siia"></textarea> </td> </tr> <tr> <td class="louna">Lõunasöök</td> <td class="userinput"><textarea name="MondayLunch" class="textarea textarealong" placeholder="Kirjuta siia"></textarea></td> </tr> <tr> <td class="oode">Oode</td> <td class="userinput"><textarea name="MondayOode" class="textarea" placeholder="Kirjuta siia"></textarea> </td> </tr> </table> <button type="submit">Submit</button> </form>

I tried adding eventListener in frontend JS file and i managed to console.log these value of the textarea everytime it is being changed, but don't know how to send them to the backend so i could add this to Database.

 var numberOfTextAreas = document.querySelectorAll('.textarea').length; for (var i = 0; i < numberOfTextAreas; i++) { document.querySelectorAll(".textarea")[i].addEventListener("change", function () { console.log('New value: ', this.value); console.log('Name: ', this.name); }); }

For backend is used express.

Thanks!

You need to use fetch API or AJAX. So every time the user changes you have to call this function:

 async function postData(url = '', data = {}) { const response = await fetch(url, { method: 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); return response.json(); } // Then you call the function like this: postData('https://example.com/autosave', { text: 'This is the text I want to save' }) .then(data => { // Autosaved successfully! });

I would recommend debounce this function or call it every time the user blurs the textarea (performance reasons).

Auto-Save forms components are using the onchange (and/or onkeyup and/or onkeydown ) attribute to register to the event and call the save method.

In addition, there is the issue of triggering to many requests. This can be solved by setTimeout and clearTimeout ;

The code will look something like this (pseudo-code):

//HTML

<form method="POST" action="/" name="myForm">
   <textarea name="textareaName_1" onchange="handleAutoSave"></textarea>
   <textarea name="textareaName_2" onchange="handleAutoSave"></textarea>
   ...
</form>
// JS
var autoSaveProgress = null;
function handleAutoSave() {

   var formData = new FormData(document.querySelector('[name]="myForm"'));

   // cancel last request
   if(autoSaveProgress){
     autoSaveProgress();
     autoSaveProgress = null;
   }

   autoSaveProgress = setTimeout(function() {
     saveToLocalstorage('KEY', formData);
   } ,1000); // 1s delay till commit 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM