Omari Victor Omosa
Omari Victor Omosa

Reputation: 2879

How to implement "user is typing" functionality and send to server

I have this code that detects whether user is typing based on this answer. I would like to send the response to the server via ajax, by placing my ajax code somewhere in the if/else statement, but am not sure how.

var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

function refreshTypingStatus() {
  if (!textarea.is(':focus') ||
      textarea.val() == '' ||
      new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
    typingStatus.html('No one is typing -blank space.');
  } else {
    typingStatus.html('User is typing...');
  }
}
function updateLastTypedTime() {
  lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

What I have tried so far:

var textarea = $('#chatbox');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

function refreshTypingStatus() {
  if (!textarea.is(':focus') ||
      textarea.val() == '' ||
      new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
    typingStatus.html('No one is typing -blank space.');
  } else {
    typingStatus.html('User is typing...');
    $.ajax({
      type: "POST",
      url: "usertypes.php?v=<?php echo $usarr; ?>",
    });
  }
}

function updateLastTypedTime() {
  lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

However, mine doesn't seem to be sending any reasponse. So I'm not sure if the placement of the ajax code is correct. Can anyone explain where am I going wrong?

Upvotes: 4

Views: 1288

Answers (2)

sharif2008
sharif2008

Reputation: 2798

Please check this again :

$(document).ready(function() {
    console.log("ready!");
    var typing = false;
    var timeout = undefined;
    var typingDelayMillis = 1000;

    function timeoutFunction() {
        typing = false;
        $.ajax({
            type: "POST",
            url: "usertypes.php?v=<?php echo $usarr; ?>&isTyping="+typing,
        });
        $('#typing_on').html("");
    }
    var delay = (function() {
        var timer = 0;
        return function(callback, ms) {
            clearTimeout(timer);
            timer = setTimeout(callback, ms);
        };
    })();

    $('#chatbox').keypress(function(e) {
        if (typing === false && $("#chatbox").is(":focus")) {
            delay(function() {
                timeoutFunction();
            }, typingDelayMillis);
            typing = true;
            $.ajax({
              type: "POST",
              url: "usertypes.php?v=<?php echo $usarr; ?>&isTyping="+typing,
            });
            $('#typing_on').html("user types...");
        }
    });

    $('#chatbox').on("blur", function() {
        clearTimeout(timeout);
        timeout = setTimeout(timeoutFunction, typingDelayMillis);
    })
});

online demo: https://jsfiddle.net/vo46gehw/5/

Upvotes: 2

Nand Kishor
Nand Kishor

Reputation: 337

Put your ajax code on keypress event.
In your case you should use your ajax code inside updateLastTypedTime function instead writing it inside callback of setInterval which executes 10 times in 1 second.

<script>
    var textarea = $('#chatbox');
    var typingStatus = $('#typing_on');
    var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
    var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

    function refreshTypingStatus() {

      if (!textarea.is(':focus') ||
          textarea.val() == '' ||
          new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
        typingStatus.html('No one is typing -blank space.');
      } else {
        typingStatus.html('User is typing...');



      }
    }

    function updateLastTypedTime() {
      lastTypedTime = new Date();

      $.ajax({
          type: "POST",
          data: {var: 'value'},
          url: "usertypes.php",
          dataType: 'json',
          success: function(response) {
            console.log(response);
          },
          error: function(jqXHR, textStatus, errorThrown) {
              // if error , code here.. 
          }
        });
    }

    setInterval(refreshTypingStatus, 100);
    textarea.keypress(updateLastTypedTime);
    textarea.blur(refreshTypingStatus);

</script>

Upvotes: 1

Related Questions