Stop the occurrence of numerous ajax requests being triggered by clicking

Having an issue with handling multiple ajax requests. In my scenario, there is a form with a button that triggers a service upon clicking it. This service is responsible for loading a list of items into a table, but currently it only loads one item at a time when the button is clicked.

The problem arises when the button is clicked multiple times - the same item gets duplicated in the table each time it's loaded.

I am looking for a solution to prevent this duplication while waiting for the response from the first request.

Current NG Service

var getItems = function () {

    var def = $q.defer();

    Items.get().then(function (items) {
       def.resolve(items);
    }, function (err) {
       ...
    });
};

I tried modifying the code like this:

var def = false;
var getItems = function () {

    def = $q.defer();

    Items.get().then(function (items) {
       def.resolve(items);
    }, function (err) {
       ...
    });
};

Setting def = false seemed to prevent duplication, but I'm unsure if this is the correct approach. Is resetting the previous request to false a valid solution?

Answer №1

To avoid multiple executions of the code simultaneously or at all, you can implement a lock on the function:

// Your service
$scope.isRunning = false;

var getItems = function () {

    if(!$scope.isRunning){
        $scope.isRunning = true;
        var def = $q.defer();

        Items.get().then(function (items) {
           def.resolve(items);
        }, function (err) {
           ...
        }).finally(function(){
             //$scope.isRunning = false; // Reset isRunning to allow for subsequent runs. Omit this line if you want it to run only once.
        });
    }
};

If you are unsure about how to handle a button that might be clicked multiple times:

You can opt to hide it upon clicking:

<button ng-hide="isRunning">Stuff</button>

Alternatively, you can disable it upon clicking:

<button ng-disabled="isRunning">Stuff</button>

If you choose to disable it, consider providing visual feedback such as changing opacity:

<button ng-disabled="isRunning" ng-class='{"opacity-half": isRunning}'>Stuff</button>
.opacity-half { opacity: 0.5 }

Answer №2

Here is a code snippet that should help achieve the desired functionality. I have intentionally avoided using some Angular-specific syntax for better understanding;

function yourContoller(/*all injectables*/) {
  var requesting = false;
  $scope.buttonClick = function() {
     if (!requesting) {
       requesting = true;
       yourService.getItems().then(function(response) {
          /*your code to handle response*/
          requesting = false;
       });
     }
  };
}

If you need to disable a button in the view, you can expose this variable by simply assigning it to scope ($scope.requesting = false;) and then use ng-disabled.

Answer №3

One way to prevent a button from being pressed twice is by creating a custom directive that disables the button after it has been clicked.

app.directive('clickAndDisable', function() {
  return {
    scope: {
      clickAndDisable: '&'
    },
    link: function(scope, iElement, iAttrs) {
      iElement.bind('click', function() {
        iElement.prop('disabled',true);
        scope.clickAndDisable().finally(function() {
          iElement.prop('disabled',false);
        })
      });
    }
  };
});

To use this directive on a button, you can do the following:

<button click-and-disable="functionThatReturnsPromise()">Click me</button>

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

Email attachments not working in Node Mailgun

I am facing an issue with my code that is designed to send emails using Mailgun in Node. The code functions as expected and sends the email successfully; however, it fails to attach the specified files. // pdfA and pdfB are both buffers defined earlier le ...

What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn& ...

displaying the print_r output of the ajax response

Feel free to modify the title! New and Improved!!! This is main.php $(document).ready(function(e) { $("#searchForm").submit(function(e) { e.preventDefault(); $("#result").load("process_search.php",{"searchKeyID":$("# ...

Adjusting the format of a JavaScript object

Looking at the object below: {A: 52, B: 33} I want to transform it into this format: ["A", 52], ["B", 33] Any recommendations on how to achieve this conversion? ...

C# MVC alert platform

Currently developing a C# MVC 4 app and aiming to integrate a notification system similar to Facebook's. I am considering implementing a table for each event to store notifications, then using AJAX calls every minute to fetch notifications for the cu ...

How to access a class from another JavaScript file using a function call

The title may seem strange, but I will do my best to explain the situation clearly. I have a website with a navigation bar where each tab corresponds to a different php file. All the files share a common js and css file. The directory structure is as foll ...

Selecting a database design pattern for varying database types

After creating a class to manage interactions with my database, I realized that I need separate classes for two different modes: admin and client. class MyDatabase { connect() { /* ... */ } } So, I decided to create two new classes: class MyDatabaseAd ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

Once lerna has the ability to handle monorepos, what benefits does Rush provide?

After thoroughly reviewing multiple datasets, it appears that Rush has a clear advantage in supporting pnpm due to its timeliness. However, it is worth noting that lerna can also offer support for pnpm: Despite this, lerna's earlier release gives it ...

Guidelines for creating animation for a single point in SVG Polygon

Is there a way to animate the movement of a single polygon point within an SVG using velocity.js? Your assistance is greatly appreciated! <p>Changing...</p> <svg height="250" width="500"> <polygon points="0,0 200,0 200,200 00,20 ...

The Angular promise refuses to resolve at my desired time

I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

What's the best way to manage endless routing options in express.js?

After reviewing the topic of handling routes in Express.js on Stack Overflow, I came across the following example : var express = require("express"); var app = express(); app.get("/", function(request, response) { response.send(&quo ...

The feature of Access Control Request Headers involves appending certain information to the header of an AJAX request when using jQuery

Looking to enhance an AJAX POST request from jQuery with a custom header. Attempted solution: $.ajax({ type: 'POST', url: url, headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } ...

Having trouble formatting the date value using the XLSX Library in Javascript?

I'm having trouble separating the headers of an Excel sheet. The code I have implemented is only working for text format. Could someone please assist me? const xlsx = require('xlsx'); const workbook = xlsx.readFile('./SMALL.xlsx') ...

Concurrent programming in Node.js with the async module

Is it recommended to avoid utilizing multiple instances of an async module feature simultaneously? In my code, there are three parts that need to be executed in sequence. The structure of my code looks like this: var async = require('async'); a ...

Learn how to remove the selected option in an angular-ui select by clicking a button

Is there a way to clear the selected option in angular ui-select when clicking on a custom clear button, rather than using the default clear (x-icon)? I have tried a few options but none seem to work. Any suggestions on how to achieve this functionality ...

recording the results of a Node.js program in PHP using exec

I'm attempting to retrieve the output from my node.js script using PHP exec wrapped within an ajax call. I am able to make the call and receive some feedback, but I can't seem to capture the console.log output in the variable. This is how I exec ...

Error 404 occurred when attempting to use the DELETE method with Spring MVC and

Can anyone help me understand this issue? Everything is working fine, except for one method that isn't functioning and keeps giving a 404 error. I have a couple of requests function deleteFunc(id) { $.ajax({ dataType: "js ...