Steps to cancel an AJAX call in C# .NET:

In the ajax.cs class, I am calling methods from the javascript side. To register this on the default.aspx page load, I did the following:

Ajax.Utility.RegisterTypeForAjax(typeof(ajax));

Occasionally, some methods take a long time to execute. In such cases, I want to be able to abort the call. How can I do this?

When calling the method from JavaScript, it looks like this:

ajax.testMethod()

Answer №1

When your controller action is set to return a Task, it allows you to include a cancellation token as a parameter. This token will be activated automatically if the HTTP request is terminated. You have the flexibility to manage this token within the action to cancel any lengthy operations as needed.

Answer №2

Have you considered cancelling the ajax request from the JavaScript side instead of aborting it from the C# side? You can set a timeout parameter in your ajax configuration that will trigger the .error() function if the timeout occurs. You can also define a callback function for when the ajax request times out.

For vanilla JavaScript:

var ajax = new XMLHttpRequest();
ajax.open('POST', 'your url');
ajax.timeout = 10000; // set timeout in milliseconds
ajax.ontimeout = function(){ } // optional callback function for timeout

For jQuery:

$.ajax({
   url: 'yoururl',
   timeout: 10000,
   error: function(){
   }
});

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

What is the best way to conditionally wrap a useState variable in an if statement without losing its value when accessing it outside the if block in reactjs?

I am facing a coding challenge with my cards state variable in React using the useState hook. I tried adding my array data to it but ended up with an empty array. Placing the state inside an if statement resulted in undefined variables. I attempted various ...

What is the best way to retrieve a parameter in jQuery ajax?

Seeking assistance with retrieving the parameter sent via ajax... url: test.htm?a=1&b=2&c=3 I am trying to access the value of b. ...

Extract a JSON substring by referencing a specific object node key

I have a JSON string that contains nested objects. Here's a portion of the JSON string: "foldChildren": "false", "branchColor": "#000000", "children": [ ...

Refresh a dynamically loaded webpage following an update

Trying to grasp the concept of reloading a dynamic page loaded with AJAX after a record is updated. Here's the jquery script on the page: <script type="text/javascript> function showUser(str) { if (str == "") { $("#txtHint").empty() ...

Having trouble with the Jquery click event not functioning on an interactive image map in Chrome browser

I currently have an interactive image-map embedded on my website. Here is the HTML code: <div id="italy-map" class="affiancato verticalmenteAllineato"> <div id="region-map"> <img src="./Immagini/transparent.gif" title="Click on ...

Searching for a specific collection item based on a custom property (excluding _id) in Meteor - what's the best approach?

I am facing an issue with my application that utilizes Flow Router along with its pub/sub functionality. I have set up a collection and template helpers. The code works fine on the client side. Template.theCase.helpers({ theCase: function () { ...

Comparison between websocket implementation in PHP and Node.js

I'm curious to learn about the distinctions between using "websocket php" and node.js for a chat feature. I currently have a chat implemented with websocket php, but I'm wondering if migrating it to node.js would be a better option. Any insights ...

The modal remains closed: Error - Attempting to access property 'open' of undefined

I've been attempting to showcase a pop-up that I implemented as a modal, but I keep getting this error: TypeError: Cannot read property 'open' of undefined The pop-up was created as a component: import { Component, OnInit, ViewChild, Ele ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Triggering an event with two clicks in JQuery

I'm facing an issue with firing 2 click events in jQuery to remove files when a RadioBoxList is selected. The buttons on the page are calling the same function as delete_Click in the code behind. Here is my current code: <asp:Button ID="delBtn1" ...

Require assistance with a situation related to an MVC route after making a jQuery AJAX request to that route

Trying to access a basic ASP.NET MVC route is resulting in an error message: The parameters dictionary contains a null entry for parameter 'isFoo' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult Tra ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

Place JavaScript buttons within a form element without triggering form submission upon clicking the buttons

Struggling to find the right words, but I'll give it a shot. I have a PHP form with multiple fields, including a textarea where I store some PHP values. I wanted to enhance the appearance of the PHP values by adding a beautifier with CSS styling. Ever ...

Removing files from the S3 bucket and database simultaneously. Execute each function sequentially

Struggling with an API call that should delete an image from both an S3 bucket and a MySQL database. However, encountering an issue where the S3 image cannot be found because it is being deleted from the database first. // Router code: //req.body is an ar ...

What is the best way to combine TypedArrays in JavaScript?

Looking to combine multiple arraybuffers into a Blob, but facing limitations with TypedArrays that lack handy methods like "push". For example: var x = new Int8Array( [ 1, 2, 3 ] ); var y = new Int8Array( [ 4, 5, 6 ] ); The desired outcome is to have [ ...

Apache2 ASP MVC Razor view encounters issues when using a Portable Class Library enum for a dropdown menu

Recently, I started using ASP.net on Ubuntu with mono and have successfully set up several websites using MVC5. However, I encountered an issue when migrating a project that includes forms referencing enums from a referenced PCL, causing views to crash. Th ...

Viewing information from DataReader within Label container (ASP.NET)

My issue involves a specific query that only returns one row, and I am struggling to find the DataSource property to display it in the Label. Can anyone provide guidance on how I can achieve this? ...

Struggling to get moment().utc() to display a two-digit format for the month and year

Currently, I am tackling a bug that has surfaced in a birthday component within my application. This component pulls the date of birth from its props in the format 1997-08-16T00:00:00Z. The challenge I am facing is that when the date of birth is set in the ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...