Prevent the query from being executed by halting the AJAX call

Within my web application, I have a specific button that triggers an AJAX call upon being clicked. On the server side, I need to run a query against a database.

I am concerned about the execution time of these queries and worry that users may be impatient and wish to stop the process mid-way. Is there a way for me to incorporate an additional button that can halt the current AJAX call and query execution? And would this be a secure method to implement?

The technologies I am working with include AngularJS on the frontend and C# on the backend.

Answer №1

more information regarding your inquiry

Implementing on the client side is simple

Tips for canceling/aborting jQuery AJAX requests

However, handling it on the server side is more complex compared to the client side. Check out this related post for further guidance

How to handle cancelling a long-running AJAX MVC action on the client side using JavaScript?

Answer №2

If you need to "cancel" a request on the client side, utilizing the $q service in AngularJS is an effective approach. By creating a deferred object and attaching it to your request using the "timeout" property in the $http({}) function call, you can easily handle cancellations.

function sendRequestToServer() {
  var canceler = $q.defer();

  var request = $http({
    method: "get",
    url: "/your/url",
    timeout: canceler.promise
  });

  var promise = request.then(function(response) {
    return response.data;
  });

  promise._canceler = canceler;

  return promise;
}


function cancel(requestPromise) {
  if (requestPromise && requestPromise._canceler && requestPromise._canceler.resolve) {  
    requestPromise._canceler.resolve();
  }
}

These functions are typically organized within the same angular service. Special thanks to Ben Nadel and his blog for the great tutorial and code!

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

When initiating a Nunit project using the command line, it scans for files within the directory specified by the nunit3-console path

When running tests, I use the command: C:\Users\user\NUnit.Console-3.17.0\bin\net6.0\nunit3-console.exe C:\Users\user\source\repos\mmfo_autotest\RegressionTestSuite\bin\Release\net6 ...

Django encounters Internal Server Error when processing an Ajax request

As someone who is relatively new to Django, I am currently exploring the use of Ajax to collect data. In addition, I am following a tutorial to create and edit a quiz app rather than building it from scratch. When I click a button, an error occurs console ...

What is the best way to enable a DOM element's height to be resized?

I have a widget displayed in the corner of my browser that I would like to make resizable by dragging the header upwards to increase its height. The widget's position remains fixed with its bottom, left, and right properties unchanged, but I need the ...

The initial component update

I am new to React and currently working on a main component that includes a child component with a table. Upon mounting, I make an API request to fetch data which is then displayed in the table. My issue arises when, after the initial update of the child c ...

WordPress does not recognize the jQuery function

I have encountered an issue with my code where a simple HTML jQuery slider works fine in a standalone file, but when I integrate it into WordPress, it no longer functions properly. The slider is being added to the index.php file by hardcoding the script li ...

The hamburger icon seems to be frozen and unresponsive

I'm struggling to get my hamburger icon to reveal the navigation bar when clicked. The icon itself functions properly and adapts to different screen sizes, but the overlay remains stationary. Check out my code on JSFiddle! <html> <head> ...

What is the best method for asynchronously injecting and providing data?

Within my page, I have implemented an asynchronous fetch method to initialize data: async fetch() { const res = await requestApi(this, '/database'); this.sliderData = res.homeSlider; this.modelData = res.model; ... } To pass thi ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

npm: generate new script directive

When I start up my NodeJs (ES6) project, I usually enter the following command in the console: ./node_modules/babel/bin/babel-node.js index.js However, I wanted to streamline this process by adding the command to the scripts section of my package.json fi ...

Email is functional on a local level, however, it is experiencing technical

I am facing an issue with sending out emails after a button click event. Everything works perfectly fine when testing from my local machine as the email is sent successfully and I receive a popup message confirming that the "call has been resolved". Howeve ...

Executing onClick event in RiotJS upon page load

As I develop a table application using RiotJS, I consistently encounter an issue with the onclick event. Whenever I attempt to utilize the <tag onclick={somefunction}> I face unpredictable behavior. Sometimes, it will excessively call the function ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Explore the steps for setting up automatic reconnection in socket.io

When establishing a socket.io connection, I use the following code: var socket = new io.connect('http://localhost:8181', { 'reconnect': true, 'reconnection delay': 500, 'max reconnection attempts': 50 }) ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Is there an alternative, more efficient method to invoke this JavaScript code received through an AJAX request?

I am curious about the use of the eval() function in my code. While it works, I have read that it is not considered best practice to use eval(). I have a scenario where I receive a response from an AJAX call, which is essentially a webpage containing some ...

Switch a Laravel Collection or Array into a JavaScript Array

Is there a way to transfer data from Laravel to a JavaScript array? I have extracted the data from my AppServiceProvider and decoded it using json_decode, as shown below: View::composer('*', function($view) { $users = Users::all(); $view-& ...

Combining platform-express and platform-fastify for optimal performance

I am currently working on a NestJS application and my goal is to upload files using the package @types/multer. However, I encountered an issue while following the guidelines from the official documentation: Upon starting my application development, I dec ...

Opting for Fetch API over Ajax for requests that involve Allow-Credentials and require POST methods

In this particular scenario, the utilization of Access-Control-Allow-Credentials accompanied by the POST method is key in managing server-side PHP session variables that need to remain stable. To provide some context, the front-end aspect involves a creat ...

Deciphering enigmatic JSON data

public abstract class A { public string Foo{ get; set; } } public class B : A { public string Marco{ get; set; } } public class C : A { public string Las{ get; set; } } public class D : A { public string Las{ get; set; } } public class ...

Encountered an error when attempting to access the property "addOption" on an undefined object

Every time I try to implement search functionality, I keep running into this error: "cannot read property 'addOption' of undefined in JavaScript selectize." I have confirmed that my result array does contain data. This is my JavaScript code: ...