An issue occurred during the AJAX request to the ASP MVC Action Controller

When clicking on a button, an AJAX request is triggered to send an ID to the controller. The server-side code runs without any errors, but within the controller action there is a section using RestSharp that makes requests to a REST web service. This part of the code is inside a loop and can run multiple times, causing the AJAX request to sometimes take too long and result in an error. What steps should be taken to address this issue?

Here is the AJAX code:


$(document).on("click", "#btn-submit", function () {
    $.ajax({
        type: 'POST',
        url: '/Panel/CheckRefOrderCode',
        data: JSON.stringify({
            factorrefid: $("#ref-check").val()
        }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.DntSuccess) {
            } else {
            }
        },
        error: function () {
        }
    });
});

The code within the action looks like this:


foreach(string s in str)
{
    var client = new RestClient("http://**.com/api/v1/orders/status?support_code=71GD4A");
    var request = new RestRequest(Method.POST);
    request.AddHeader("token", "15befa43");
    IRestResponse response = client.Execute(request);

    RefOrderJsonViewModel.RefOrderJson reforderbackJson =
        JsonConvert.DeserializeObject<RefOrderJsonViewModel.RefOrderJson>(response.Content);

    if (reforderbackJson.status.ToLower() == "ok")
    {
        performed += reforderbackJson.data.performed;
        order_status += reforderbackJson.data.order_status + "^";
    }
}

In addition, changes were made to the web.config file:


<httpRuntime executionTimeout="100000000" maxRequestLength="262144" />

Answer №1

Implementing a timeout feature in the ajax call:

 $(document).on("click", "#btn-submit", function () {
                $.ajax({
                    type: 'POST',
                    url: '/Panel/CheckRefOrderCode',
                    data: JSON.stringify({
                        factorrefid: $("#ref-check").val()
                    }),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    **timeout: 10000 // setting timeout to 10 seconds**
                    success: function (result) {
                        if (result.DntSuccess) {
                        } else {
                        }
                    },
                    error: function () {
                    }
                });
        });

For more information on handling timeout errors, refer to this helpful post.

Answer №2

The issue persists;

However, I have found a solution:

Parallel.ForEach(myEnumerable, obj =>
{
   // ... 
});

instead of the traditional

foreach

and executing the body of foreach in parallel. As a result, the processing time has decreased and the problem has been resolved.

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

Efficient way to handle nested variables in templates with Nunjucks or alternative approaches

Recently I've been exploring the world of gulp and nunjucks templating, specifically for creating emails. One challenge I'm facing is figuring out how to call a module/partial and assign different values to its attributes each time it's pro ...

A JavaScript function that instantiates an object that invokes its own function

Currently, I am working on an Angular service that is meant to return a new object. Everything seems to be fine and in working order. When I use new MakeRoll(), it successfully creates an instance. However, the issue arises when I call self.add towards th ...

Is it possible to automatically redirect to a different URL if the server is running slow when clicking?

Is it possible to utilize Javascript, AJAX, or another client-side technology to automatically redirect the user to a different URL if the initial URL is slow to respond when clicked on? For example, if a link redirects to URL1 and there is no response fr ...

The bootsrtap modal appears to be invisible and is not displaying on the screen

Having trouble implementing a code to display a bootstrap modal upon clicking a button. The modal is not showing up for some reason. Here is the code snippet: <button type="button" id="asd" data-toggle="modal" data-target= ...

Choose an option with JavaScript once the request is successful

Choose the day, month, and year using JSON data success: function(jsondata){ var data=JSON.parse(jsondata); var list_html="<div id='editrelation'><label id='dateLabel' style='display:none&apo ...

Unable to perform real-time transpilation of ES module, a loader plugin must be set up through the SystemJS.config configuration

I encountered an issue while trying to develop a plugable application. Everything was functioning correctly until I introduced "ngx-bootstrap" and "FullCalendarModule"/primeng in the plugin app. Importing any of these modules resulted in the following erro ...

Identifying the active input using React hooks

Currently exploring React Hooks and trying to determine which input is currently in focus. I have a collection of inputs that are generated dynamically, and I would like to identify the selected one so that I can append a value to it upon button click. ...

Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name. However, after clicking on o ...

Leveraging Promises in AngularJS to create a chain between two separate controllers

I've developed a provider called MyRestServices to handle my REST-Services: app.provider('MyRestServices', function() { this.baseUrl = null; this.setBaseUrl = function(_baseUrl) { this.baseUrl = _baseUrl; }; this.$get = [' ...

Combine two objects within Three.js to create a single entity

I've developed a function that generates spheres for each vertex of a geometry and positions them accordingly. For instance, if there's a cube, the function will create a sphere for each vertex of the cube. function makeSphereVertices(){ console ...

Angular has been modified after being verified. The earlier value was 'null'

core.js:6162 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null'. Current value: '{ When attempting to retrieve the {{dispositionDetails?.metricsData | json}} ...

Populate DataGrid using an input through AJAX and jQuery technology

I've been grappling with a persistent issue that's been bothering me for days now. Here's the scenario: Currently, I have a DataGrid that is empty and an Input Text field in place that utilizes AJAX and jQuery to display a list of available ...

Can you save updates made to your application configuration in the app.config file of your application through serialization?

Is there a native way to automatically serialize changes made to the app.config file using the built-in functions provided by .NET? For example, if a custom property in Executable.exe.config changes during runtime, can .NET automatically update the Execut ...

Interacting between Jquery and servlets using AJAX

In order to establish communication between a Jquery function and a servlet in Tomcat, I have created the following code snippets. Servlet Code: import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; i ...

Generating a personalized list of objects from JSON information

My json objects array contains the following data: [{"SensorID":2,"Temperature":34.0,"Humidity":56.0,"Carbon":87.0,"DateTime":"2017-03-08T10:07:00","ID":10},{"SensorID":2,"Temperature":34.0,"Humidity":43.0,"Carbon":87.0,"DateTime":"2017-03-09T12:00:00","I ...

Developing an if-else statement to showcase a different div depending on the URL

Having trouble with an if/else statement to display one div or another based on the URL: No matter what I try, only "Div 1" keeps showing. Here's my code snippet: <script> if (window.location.href.indexOf("pink") > -1) { document.getElemen ...

JavaScript code encounters an error stating "TypeError: n is undefined"

I recently crafted a JavaScript script to accomplish a specific task, and overall it was working smoothly. However, as I attempted to simplify the code for a demonstration here on this platform, I encountered two issues. Unfortunately, during this 're ...

Is it possible to execute a function once an element has finished loading?

I am facing a challenge with running the List_Sandbox functions after a specific each loop. This loop selects checkboxes that trigger a change event, rendering additional checkboxes that need to be selected. The issue arises when the List_Sandbox functio ...

Create a base data model that can be duplicated and modified as needed

In my two-player game, both players start with similar data that evolves as the game progresses. I believe I need to create a constructor object that can be duplicated and modified, while also being in JSON format for easy ajax sending. Is there a design ...

The Node API is unresponsive when using Postman or accessing through the browser, as it is not returning any status code. However, no errors are displayed when

I am currently working on developing a Node API for an employee department model. I have created various requests such as 'GET', 'PUSH', 'PATCH', and 'DELETE' for both the employee and department endpoints. This deve ...