Send keystrokes with ajax after 1 s?

I want to send keystrokes in a text box, but only after 1 s.

this will reduce the burden of sending an ajax request for every keystroke.

for example. if the user enters 4 letters in one second, the request will send all these 4 letters. and allows you to say that it enters non-stop after 1 minute, then the script will send at 1-second intervals until it stops typing.

currently my script is as follows:

$("#type_post").live('keyup', function() {
      $.post('posts.php', {post: $("#type_post").val()});
});

but it sends out all keystrokes.

Can anyone help me here.

UPDATE: here is the code I used.

var last_post = '';

$('#type_post').focus(function() {
     // check if text has been changed every second when input field is focused
     setInterval(function() {
          if($('#type_post').val() != last_post)
          {
               // if changed, post it and set the new text as last text
               $.post('posts.php', {post: $("#type_post").val()});
               last_post = $("#type_post").val();
          }
     }, 1000);
});
+3
source share
6 answers

, , , setTimeout() (info here) . , ajax.

, , , "focus" "blur".

+4

, , .

+3

AJAX . setTimeout clearTimeout , . .

var timer = 0;
$("#type_post").live('keyup', function(e) {
    var val = $(this).val();
    // clear any existing timer
    clearTimeout(timer);
    // set a 1 second timeout
    timer = setTimeout(function() { keyLogger(val) }, 1000);
});

function keyLogger(val) {
    $.post('posts.php', {post: $("#type_post").val()});
}
+3

, , , 4 - , -. , - , .

, , . - , , , - , . , .

var sendInterval;
var lastValue;
$("#type_post").focus(function() {
         var input = $(this);
    sendInterval = setInterval(function() { sendData(input.val()); }, 4000);
});

$("#type_post").blur(function() {
    if(sendInterval)
        clearInterval(sendInterval);
});

function sendData(data) {
    if(lastValue !=  data) {
        lastValue = data;
        $.post('posts.php', {post: data});
    }
}
+3

Ajax jQuery 1.1, , , OnKeyUp:

  clearInterval(this.onChangeInterval);
  if (this.currentValue !== this.el.val()) {
    if (this.options.deferRequestBy > 0) {
      // Defer lookup in case when value changes very quickly:
      var me = this;
      this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
    } else {
      this.onValueChange();
    }
  }

, .

+1

- , MooTools jQuery... http://obviousspoilers.com/member/register ( ).

, JavaScript, onkeyup = "..." onblur = "...". , . JavaScript http://obviousspoilers.com/res/script.js, Register.

: , , , : (

+1

Source: https://habr.com/ru/post/1728551/


All Articles