title: Ajax call after reading the current text input value
body: <p>I am following this answer <a href="https://stackoverflow.com/a/20698523/1695685">https://stackoverflow.com/a/20698523/1695685</a> in order to read value from a handheld barcode scanner. The code works fine as mentioned in the answer (fiddle is attached in the above link)</p>
  
  <p>However, what I am trying to do is to make some ajax calls based on the <strong>current</strong> value of text input after reading a barcode.</p>
  
  <p>The problem I'm facing is that if I scan barcode multiple times I am making ajax calls the same number of times after I press a button (which triggers the ajax call). For e.g. If I read 4 barcodes, I am making the same ajax call( in my case <a href="http://localhost:51990/Home/DecodeScanner" rel="nofollow noreferrer">http://localhost:51990/Home/DecodeScanner</a>) 4 times. What I am after is to make only one call after pressing a button, but only read the latest value from the text input box.</p>
  
  <p>Every time I can scan a barcode the text input box is showing the new value (previous values are overridden). However, the ajax call is firing all the previous scans as well on pressing <code>#scanner-verify-button</code> button.</p>
  
  <p>This is my modified <a href="http://jsfiddle.net/Bf89R/475/" rel="nofollow noreferrer">Fiddle</a> with my custom ajax calls</p>
  
  <pre><code>/*
      This code will determine when a code has been either entered manually or
      entered using a scanner.
      It assumes that a code has finished being entered when one of the following
      events occurs:
          • The enter key (keycode 13) is input
          • The input has a minumum length of text and loses focus
          • Input stops after being entered very fast (assumed to be a scanner)
  */
  
  var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
  var minChars = 3;
  
  // handle a key value being entered by either keyboard or scanner
  $("#scanInput").keypress(function(e) {
    // restart the timer
    if (timing) {
      clearTimeout(timing);
    }
  
    // handle the key event
    if (e.which == 13) {
      // Enter key was entered
  
      // don't submit the form
      e.preventDefault();
  
      // has the user finished entering manually?
      if ($("#scanInput").val().length &gt;= minChars) {
        userFinishedEntering = true; // incase the user pressed the enter key
        inputComplete();
      }
    } else {
      // some other key value was entered
  
      // could be the last character
      inputStop = performance.now();
      lastKey = e.which;
  
      // don't assume it's finished just yet
      userFinishedEntering = false;
  
      // is this the first character?
      if (!inputStart) {
        firstKey = e.which;
        inputStart = inputStop;
  
        // watch for a loss of focus
        $("body").on("blur", "#scanInput", inputBlur);
      }
  
      // start the timer again
      timing = setTimeout(inputTimeoutHandler, 500);
    }
  });
  
  // Assume that a loss of focus means the value has finished being entered
  function inputBlur() {
    clearTimeout(timing);
    if ($("#scanInput").val().length &gt;= minChars) {
      userFinishedEntering = true;
      inputComplete();
    }
  };
  
  
  // reset the page
  $("#reset").click(function(e) {
    e.preventDefault();
    resetValues();
  });
  
  function resetValues() {
    // clear the variables
    inputStart = null;
    inputStop = null;
    firstKey = null;
    lastKey = null;
    // clear the results
    inputComplete();
  }
  
  // Assume that it is from the scanner if it was entered really fast
  function isScannerInput() {
    return (((inputStop - inputStart) / $("#scanInput").val().length) &lt; 15);
  }
  
  // Determine if the user is just typing slowly
  function isUserFinishedEntering() {
    return !isScannerInput() &amp;&amp; userFinishedEntering;
  }
  
  function inputTimeoutHandler() {
    // stop listening for a timer event
    clearTimeout(timing);
    // if the value is being entered manually and hasn't finished being entered
    if (!isUserFinishedEntering() || $("#scanInput").val().length &lt; 3) {
      // keep waiting for input
      return;
    } else {
      reportValues();
    }
  }
  
  // here we decide what to do now that we know a value has been completely entered
  function inputComplete() {
    // stop listening for the input to lose focus
    $("body").off("blur", "#scanInput", inputBlur);
    // report the results
    reportValues();
  }
  
  function reportValues() {
    // update the metrics
    $("#startTime").text(inputStart == null ? "" : inputStart);
    $("#firstKey").text(firstKey == null ? "" : firstKey);
    $("#endTime").text(inputStop == null ? "" : inputStop);
    $("#lastKey").text(lastKey == null ? "" : lastKey);
    $("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
    if (!inputStart) {
      // clear the results
      $("#resultsList").html("");
      $("#scanInput").focus().select();
    } else {
      // prepend another result item
      var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
      $("#resultsList").prepend("&lt;div class='resultItem " + inputMethod + "'&gt;" +
        "&lt;span&gt;Value: " + $("#scanInput").val() + "&lt;br/&gt;" +
        "&lt;span&gt;ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "&lt;/span&gt;&lt;/br&gt;" +
        "&lt;span&gt;InputMethod: &lt;strong&gt;" + inputMethod + "&lt;/strong&gt;&lt;/span&gt;&lt;/br&gt;" +
        "&lt;/span&gt;&lt;/div&gt;&lt;/br&gt;");
      $("#scanInput").focus().select();
      inputStart = null;
  
      // Some transformations
  
      const barcodeString = $("#scanInput").val();
  
      const productCode = barcodeString.substring(5, 19);
      const serialNumber = barcodeString.substring(36, 46);
      const batch = barcodeString.substring(29, 34);
      const expirationDate = barcodeString.substring(21, 27);
  
      // AJAX calls
      $('#scanner-verify-button').click(function() {
        $.ajax({
          url: "DecodeScanner",
          type: "POST",
          data: {
            productCode: productCode,
            serialNumber: serialNumber,
            batch: batch,
            expirationDate: expirationDate,
            commandStatusCode: 0
          },
          async: true,
          success: function(data) {
            $('#pTextAreaResult').text(data);
          }
        });
      });
    }
  }
  
  $("#scanInput").focus();
  </code></pre>
  
  <p>HTML</p>
  
  <pre><code>&lt;form&gt;
      &lt;input id="scanInput" /&gt;
      &lt;button id="reset"&gt;Reset&lt;/button&gt;
  &lt;/form&gt;
  &lt;br/&gt;
  &lt;div&gt;
      &lt;h2&gt;Event Information&lt;/h2&gt; Start: &lt;span id="startTime"&gt;&lt;/span&gt;
      &lt;br/&gt;First Key: &lt;span id="firstKey"&gt;&lt;/span&gt;
      &lt;br/&gt;Last Ley: &lt;span id="lastKey"&gt;&lt;/span&gt;
      &lt;br/&gt;End: &lt;span id="endTime"&gt;&lt;/span&gt;
      &lt;br/&gt;Elapsed: &lt;span id="totalTime"&gt;&lt;/span&gt;
  
  &lt;/div&gt;
  &lt;div&gt;
      &lt;h2&gt;Results&lt;/h2&gt;
  
      &lt;div id="resultsList"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="col-sm-12"&gt;
      &lt;button id="scanner-verify-button" type="submit"&gt;Verify&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>