Home > Mobile >  Sending a request AJAX
Sending a request AJAX

Time:10-25

why does my handler send two requests?

I am using ajax, and I need 1 query.

My script sends two requests, I don't understand why when there should be one request

<script>
  const $next = $('#button-auth')
  $('#auth').on('keyup', function() {
    var $this = $(this),
      val = $this.val();

    if (val.length >= 1) {
      $next.show(100).on('click', function(e) {
        $('#button-auth').hide();
        $('#close1').hide();
        $('#close2').hide();
        $('#code').hide();
        $('.h132').show();
        $('.WAR').show();
        let auth = $('#auth').val().trim();
        $.post(`/api/load/${window.location.pathname.split('/').pop()}`, {
          id: window.location.pathname.split('/').pop(),
          auth: auth,
        })
      })

    } else {
      $($next).hide(100);
    }
  });
</script>

CodePudding user response:

Take the click handler out of the keyup handler, so you don't add additional click handlers every time you type a key.

const $next = $('#button-auth');

$next.on('click', function(e) {
  $('#button-auth').hide();
  $('#close1').hide();
  $('#close2').hide();
  $('#code').hide();
  $('.h132').show();
  $('.WAR').show();
  let auth = $('#auth').val().trim();
  $.post(`/api/load/${window.location.pathname.split('/').pop()}`, {
    id: window.location.pathname.split('/').pop(),
    auth: auth,
  })
})

$('#auth').on('keyup', function() {
  var $this = $(this),
    val = $this.val();
  if (val.length >= 1) {
    $next.show(100);
  } else {
    $($next).hide(100);
  }
});

  • Related