2

I am attempting to stop the previous AJAX request when a new keyup event fires. The patten is like this:

  1. User enters A, my code will submit the form using AJAX with a test_value of A.
  2. When user enters B I want to stop the AJAX request from the first step and make a new request with test_value of AB.
<input type="text" id="xxx" onkeyup="test_fn(this.value)" autocomplete="off">
<div id="loading" style="display: none;">please wait.....</div>
<span id="myplace_test"></span>
<form id="test_fid" method="POST" action="" style="display: none;">
  <input type="text" name="test_value" id="test_value">
</form>
  function test_fn(val) {
    document.getElementById("loading").style.display = "block";
    document.getElementById("test_value").value = val;
    $.ajax({
      url: "test.php",
      type: "POST",
      data: $('#test_fid').serialize(),
      cache: false,
      success: function(data) {
        $('#myplace_test').html(data);
        document.getElementById("loading").style.display = "none";
      }
    });
  }
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Already answered this question : https://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up – Mohan Rajput Oct 22 '18 at 07:15

1 Answers1

1

To achieve what you require you can save a reference to the previous AJAX request in a variable and then call abort() on that if a new keyup event fires.

Also note that you shouldn't be using on* event attributes. As you've included jQuery in the page, you can use that to attach unobtrusive event handlers. You can also use jQuery to select your elements and work with them more succinctly. Try this:

<input type="text" id="xxx" autocomplete="off">
<div id="loading">please wait.....</div>
<span id="myplace_test"></span>
<form id="test_fid" method="POST" action="">
  <input type="text" name="test_value" id="test_value">
</form>
var activeRequest;

$('#xxx').on('keyup', function(e) {
  $("l#oading").show()
  $("#test_value").val(this.value);
  activeRequest && activeRequest.abort();

  activeRequest = $.ajax({
    url: "test.php",
    type: "POST",
    data: $('#test_fid').serialize(),
    cache: false,
    success: function(data) {
      $('#myplace_test').html(data);
      $("#loading").hide();
    }
  });
});
#loading,
#test_fid { 
  display: none; 
}

Also note the use of CSS to contain the styling rules instead of placing them inline in the HTML.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339