I have a lot of textareas on a page and want to save the contents automatically by typing inside
$('textarea').on('input', function(){
let id = $(this).attr('data-id');
let story = $(this).val();
$.post('a_pro.php', {fn: 'tx_change', args: [id, story]}, function(data){
console.log('saved');
});
});
On server side I have a php
function tx_change
to store data in a mysql
table.
Everything works fine, regardless what is the speed of typing, regardles I'm on a wire on wireless connection...
I even tried typing inside one textarea and at the same time pasting a content inside another one - it works - everything is saved.
Question is - why people use a SAVE button at all?
I suppose there is a hidden risk of using this?
In a second I type 4-5 characters, so each second the javascript
, php
and sql
code is executed five times, and plus time for establishing connection and plus time for callback function (write console)...
I simply cannot believe that there is no any problem with this.
Any advice?
Yes that true you will increase overhead on server using auto save method.
if you still want auto save, you should decrease number of request and you can do it by using debounce function.
const debounce = (func, delay) => {
let debounceTimer
return function() {
const context = this
const args = arguments
clearTimeout(debounceTimer)
debounceTimer = setTimeout(() => func.apply(context, args), delay)
}
}
var textareaElem = document.getElementById("textarea");
textareaElem.addEventListener('keyup', debounce(function() {
alert("Hello\nNo matter how many times you" +
"click the debounce button, I get " +
"executed once every 300 ms!!")
}, 300)); // <-- you can change debounce time
<textarea id="textarea"></textarea>