abetwothree
abetwothree

Reputation: 577

How to only get variable every few seconds and update it

I have a form where maintenance employees at my company fill out at the end of the day to describe what they did that day. Some fill it out on their phones sometimes. They complained that if they got a call or text they would loose their log they had typed up.

So what I did is store the form values into PHP SESSION variables via AJAX and echo out the variable if the form is reloaded as long as they're signed in.

This is one of input fields:

<textarea class="form-control" name="8to10" id="d8to10" placeholder="8 to 10 am" rows="8">
  <?php if(isset($_SESSION['d8to10'])){echo htmlspecialchars($_SESSION['d8to10'], ENT_QUOTES);} ?>
</textarea>
<span id="saved1"><span>

This is the corresponding Javascript that grabs the field's value and sends it through AJAX to get store into the SESSION variable.

$('#d8to10').on("keyup", function(){

    var d8to10 = $(this).val();
    $('#saved1').css('display', 'none');

    d8to10 = encodeURIComponent(d8to10);
    //console.log(d8to10);

    var ajaxRequest;
    clearTimeout(ajaxRequest);
        ajaxRequest = setTimeout(function() {

            $.ajax({
                type: 'post',
                url: 'Includes/dailyLogCacheLog.php',
                data: 'd8to10=' + d8to10,
                success: function(r) {
                    $('#saved1').css('display', 'inline');
                    $('#saved1').html('<p>Saved</p>');
                }
            });
        }, 3000, d8to10);

});

So what I want to do now and can't figure out how to do right is to only grab the variable every 5 or 10 seconds as they type and save it in that time frame. This is because now the AJAX is being called after every letter typed up and they're complaining that the saved message is blinking too much.

Anyone know a way to do this?

Upvotes: 2

Views: 1935

Answers (3)

LSauchelli
LSauchelli

Reputation: 36

Something like this might do the trick, this basically only executes the ajax about three seconds after the user stops typing. If you want to have multiple calls while the user types, you can remove the clearTimeout and abort calls.

var timeout_d8to10;
var xhr_d8to10;
$('#d8to10').on("keyup", function(){
    var $this = $(this);
    if (timeout_d8to10) {
        clearTimeout(timeout_d8to10);
    }
    if ( xhr_d8to10) {
        xhr_d8to10.abort();
    }
    timeout_d8to10 = setTimeout( function () {
        var d8to10 = $this.val();
        d8to10 = encodeURIComponent(d8to10);

        $('#saved1').css('display', 'none');
        xhr_d8to10 = $.ajax({
            type: 'post',
            url: 'Includes/dailyLogCacheLog.php',
            data: 'd8to10=' + d8to10,
            success: function(r) {
                $('#saved1').css('display', 'inline');
                $('#saved1').html('<p>Saved</p>');
            }
          });

    }, 3000);
});

Upvotes: 2

Dustin Stiles
Dustin Stiles

Reputation: 1424

If your intent was to have the Auto-Save feature of the field, similar to how gmail would save drafts, then I believe you are going to need a separate ajax call. As bwegs suggested, use a setInterval. If you absolutely must keep the keyup call, then just add something like this below it

function getFreshValue() {
  var newVal;

  $.get('someUrl')
    .then(function(data) {
      // Logic that handles inserting the new value
      // and / or making sure there is a valid value first
    });
}

setInterval(getFreshValue, 7500) // 7.5 second interval

EDIT: I really don't think there is a way to get around this without multiple calls. Unless you do it on an interval of keystrokes (every 10-15 keypresses for example).

Hoping someone else can do better?

Upvotes: 1

bwegs
bwegs

Reputation: 3767

Instead of firing your ajax on every keyup event when the document loads put your ajax call in a setInterval function that saves the contents of the textarea at the desired interval:

var saveInterval; // to store ID in case you want to stop this later

$(document).ready(function() {
    // call saveContent every 3 seconds
    saveInterval = window.setInterval(saveContent, 3000);
});

function saveContent() {
    var d8to10 = $(this).val();
    $('#saved1').css('display', 'none');

    d8to10 = encodeURIComponent(d8to10);
    //console.log(d8to10);

    var ajaxRequest;

    ajaxRequest = function() {

        $.ajax({
            type: 'post',
            url: 'Includes/dailyLogCacheLog.php',
            data: 'd8to10=' + d8to10,
            success: function(r) {
                $('#saved1').css('display', 'inline');
                $('#saved1').html('<p>Saved</p>');
            }
        });
    }, d8to10);
};

Upvotes: 1

Related Questions