Initiating an AJAX call

What is causing my handler to send multiple requests?

With the use of Ajax, I am expecting only one query.

However, my script seems to be sending two requests instead of just one, which is confusing to me.

<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>

Answer №1

Separate the click handler from the keyup handler to avoid adding extra click handlers each time a key is pressed.

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);
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The color change functions are functional in IE9 and Firefox, but may not be compatible with earlier versions of IE or Chrome

A JavaScript function is used to change the colors of CSS rendered images in Internet Explorer 9 and Firefox. Is there a workaround for this issue or is it related to the code on the page? You can see this in action at . <!DOCTYPE html PUBLIC &quo ...

Is it possible to eliminate all inline styles on a parent element using a child element in CSS?

I'm currently working on an Angular project and I need to remove the styling of the parent element by using the child element, based on certain conditions. It's important to note that the parent element has inline styling. My code looks somethin ...

What is the best way to reverse the order of objects in a JSON parsed object?

In my possession is an object {"5":"5","4":"4","3":"3","2":"2","1":"1","-1":"P1",-2":"P2"} Utilizing this specific function to interpret the elements: function floormake(inobj) { var levels = ''; var obj = JSON.parse(inobj); levels + ...

Why is it that every time I install an npm package, it triggers a re-installation of all

Whenever I attempt to install a new package using npm, I face a frustrating problem where it also starts to install all of my other packages, leading to potential breakage and the need to reinstall my node modules. I am puzzled by this behavior and unsure ...

JavaScript: What's the best way to update the URL in the address bar without triggering a page refresh?

Similar Question: How can I use JavaScript to update the browser URL without reloading the page? I've observed websites like GMail and GrooveShark altering the URL in the address bar without having to refresh the entire page. Based on my understa ...

Using useState in next.js with Link component for navigation (next/link)

In my next.js page, I have a setup to display blog posts and use the Link component to navigate between them. To properly display the post content, I utilize another component as shown below: const Index: NextPage<PageProps> = (props) => { con ...

The preventDefault() function is not functioning properly on the <a> tag

As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program. In this scenario, uppercase letters represent first-level menus while lowercase letters repr ...

Guide to loading a different domain page with JavaScript

Looking to enhance a page on my site (let's say it's on domain A) by pulling in additional content from another page, located on domain B. However, browsers typically block this functionality for security purposes. After researching, I've c ...

Ajax: Cross-Domain Request Blocked: The Same-Origin Policy prevents access to the external resource at

I am running an MVC Web API Service on two servers. When accessing it through C# using WebClient and HttpClient, as well as through Postman or directly pasting the service URL in the browser, everything works fine. However, when trying to consume it throug ...

incapable of modifying the contents of an array

Struggling with a JavaScript issue (not angular related, but within an Angular context) for hours without any success. I've condensed the content into shorter paragraphs and reassigned the subcontent back to the array's content property, but the ...

Using React and Ant Design: Sharing state between multiple <Select> components within a <Form> element

Just getting started with ReactJS and AntDesign. Currently, I am working on connecting a series of <Select> components to share state. The goal is for the selection made in the first dropdown to dynamically update the options available in the follow ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Dynamic Node.js server constantly updating

My goal is to create a dynamic Node.js Express server that updates live, possibly by creating a specific route like /update to load a new configuration file. My concern is that the server could be in any state when the update occurs. It's possible tha ...

"Unlocking the Dialog Box: A Step-by-Step Guide to Programatically Opening Material UI Dialog

Typically, Material UI's Dialog is used as shown below, following the documentation: export default function AlertDialog() { const [open, setOpen] = React.useState(false); const handleClickOpen = () => setOpen(true); const handleClose = () =& ...

iOS Safari does not support equivalent regex unsupported lookbehind assertion

Trying to break a string into sentences using regex can be tricky. Unfortunately, the regex used in this example: var text = "Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn ...

Spinning a CSS object around an axis

Trying to add a unique touch to my image rotation with CSS. While familiar with rotating around x, y, and z axis, I want to achieve a diagonal rotation this time. Wondering if there's a way to tweak the y axis for a more slanted effect on my image? ...

The ASP.Net email contains a hyperlink designed to open in a new window

I am currently facing an issue with an email I need to send. The problem lies in the hyperlink that is intended to open a specific page in a new tab or window upon clicking. The main issue at hand is that there is no space between the querystring variable ...

Explore and recommend the keywords available in the drop-down menu

Currently, I am working with php and javascript. I have successfully created a dropdown menu using the provided code. However, I now need assistance in developing a feature where I can input a word into a text box and have suggestions generated from the ...

Ever since transitioning to Discord.js 13, why am I suddenly encountering a bug with the messageCreate event?

I'm encountering an issue with my external js file for Events in messageCreate.js. It seems like certain functionalities are not working correctly, even though they were functioning fine with Discord.JS version 12. For instance, when I try to return ...

Activating Bootstrap modal when a navigation link is clicked

Just started a site for a client and new to Bootstrap. I've got the layout down - full-width page with "Top Nav" within the nav bar, looking to create a modal effect drop-down. When clicking on "About", it should trigger the .modal function. However, ...