Making an Ajax request to retrieve progress information by utilizing IProgress

I have encountered an issue with my code involving 2 ajax API calls. One call fetches data through a lengthy process, while the other retrieves progress values using the IProgress interface and runs every 5 seconds. The value from ReportProgress successfully updates and is assigned to the _generateRecipeCardsStatus property. However, when I call getProgress() -> GeneratePrintRecipeCardsStatus, the _generateRecipeCardsStatus property always remains zero. Can anyone help me identify where I may be going wrong?

    <script>
        getData();
        getProgress()
    
        // long process
        function getData() {
            const token = $('input[name="__RequestVerificationToken"]').val();
        
            $.ajax({
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    "X-ANTI-FORGERY-TOKEN":  token
                },
                type: 'POST',
                url:  `@Url.Action("GeneratePrintRecipeCards", "MenuPrintout")?id=` + @Model.RecipeCardLabelId + `&menuHeaderId=` + @Model.MenuHeaderId, 
                success: function(response){
                     console.log(response)
                     const { errorMsg, progressValue } = response
        
                    inProgressEle.hide();
                    close.show();
        
                    if (errorMsg) {
                        toast(errorMsg, "error")
                    }
                    else if (progressValue > 0) {
                        console.log("progress value:" + progressValue);   
                    }
                    else{ 
                        expand.hide()
                        collapse.hide()
                        statusEle.text("Ready");
                        completedEle.fadeIn() 
                    }
                }
            });
        }
        
         // get progress
        function getProgress() {
             setInterval(function(){ 
                $.ajax({
                    url: '@Url.Action("GeneratePrintRecipeCardsStatus", "MenuPrintout")', 
                    type: "GET",
                    success: function (response) {
                        console.log(response)
                        $('#lblStatus').text(response)
                    }
                })
            }, 5000)
        }
 </script>
 

// controller
public class MenuPrintoutController : BaseController
{
    private readonly IMenuLabelService _menuLabelService;
    private int _generateRecipeCardsStatus;

    private Progress<int> _progress;
    
    public MenuPrintoutController(IMenuLabelService menuLabelServicee)
    {
        _menuLabelService = menuLabelService;
    }
    
    // Is always zero
    public int GeneratePrintRecipeCardsStatus()
    {
        return _generateRecipeCardsStatus;
    }

    // Updates fine 
    private void ReportProgress(int progress)
    {
        _generateRecipeCardsStatus = progress;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> GeneratePrintRecipeCards(int id, int menuHeaderId)
    {
        try
        {
            _progress = new Progress<int>(ReportProgress);
            
            var data = await _menuLabelService.DoAsync(int menuHeaderId, _progress);
            
            TempData.Put("PrintRecipeCards", data);
            
            return Json(new { Success = true });
        }
        catch (Exception exp)
        {
            return Json(new { ErrorMsg = exp.Message });
        }
    }
}

// service
public interface IMenuLabelService
{ 
    Task<object> DoAsync(int menuHeaderId, IProgress<int> progress);
}

public class MenuLabelService : IMenuLabelService
{
    public async Task<object> DoAsync(int menuHeaderId, IProgress<int> progress) 
    {
        var menuFoodItemsList = _context.FoodItemUnits
            .Where(x => x.MenuSectionFoodItemUnits.Any(y => y.Menusection.MenuheaderId == menuHeaderId))
            .Select(x => x.Fooditem)
            .ToList();
            
        var menuFoodItems = new List<PrintLabel>();
         var donePointer = 0;
         
        foreach (var menuFoodItem in menuFoodItemsList)
        {
            menuFoodItems.Add(menuFoodItem);
            // ...
            
            progress.Report((int)(++donePointer / (double)menuFoodItemsList.Count * 100));
            donePointer++;
        }
        
        return menuFoodItems;
    }
}

Answer №1

For each request, a new controller is generated, resulting in two distinct _generateRecipeCardsStatus variables.

To support a single call on one server only, you can simply declare the variable as static.

If multiple calls are needed, then an identifier/lookup system must be implemented. It's important to also have a way to remove old statuses that are no longer necessary, turning this lookup into more of a cache than a dictionary.

If deployment across multiple servers is desired, an external cache should be used instead of storing data in memory.

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 faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Developing a personalized Markdown-it extension for a Nuxt web app causes a Type Error while displaying in a web browser

I have been working on developing a Nuxt.js application utilizing markdown rendering with markdown-it. To achieve this, I created a custom plugin located in the "helpers" directory. nuxt.config.js ... modules: [ ..., '@nuxtjs/markdownit', ] ...

Is there a way to send an AJAX request to an MVC action from a JavaScript file?

In a file named job.js, there is code that works perfectly when run on localhost but results in a 404 error when run on an intranet server with an application name. Job.updateJob = function () { $.post('/Builder/ListJobItems', function (dat ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Having trouble making an Ajax request in Rails3

I am currently in the process of refactoring my project by incorporating AJAX functionality. I have a link that triggers an action in a controller: = link_to("Please work", "show_recent_chart", :remote => true) This links to a specific controller acti ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Increase the current time by 50 minutes

I have a dropdown menu with various time options like this: <select name="" id="delyvery-hour"> <option value="18:00">18:00</option> <option value="18:05">18:05</option> <option ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

Is there an implicit dependency on mscorlib v4 in a new .NET 2.0 C++/CLI project?

After setting up a new C++/CLI project in Visual Studio 2012, I made sure to select .NET 2.0 as the framework during project creation. The "External Dependencies" like mscorlib.dll, System.Data.dll, System.dll, and System.XML.dll were all showing the path ...

Organize all ngDialog instances within a factory and access them through a directive

In order to keep the ngDialogs centralized in one place instead of dispersed, I had the idea of creating a factory named modal.js. This factory would contain a list of all the modals with a switch statement. Here is an example: .factory(&ap ...

Error: Unable to modify the div content - Uncaught TypeError: Unable to assign value to innerHTML of null

Attempting to update the contents of a div using JavaScript and innerHTML, but encountering an issue. After implementing the code to change the div's content, the functionality stopped working. The syntax has been double-checked. Tools being used in ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

Utilizing a single variable across different JavaScript scripts - where one script includes a .ready function while the other does not

I am facing a challenge with 2 javascript scripts that I have: <script type="text/javascript"> function capture(){ var canvas = document.getElementById('canvas'); var video = document.getElementById('video'); canvas.getContext ...

Unpacking Functions within Embedded Redux Reducer

My current challenge involves dispatching an action that has the following structure: { type: "TOGGLE_FARA", fara: true, id: "5d20d019cf42731c8f706db1" } The purpose of this action is to modify the "enabled" property within my "fara" state. The configura ...

Trigger an Ajax upload by clicking a different element than the upload button

Currently, I am using Ajax Upload to sequentially upload a maximum of 6 images. Each image has its own corresponding div in the layout, and I want the upload action to be initiated when I click on these divs. However, my attempt at achieving this functiona ...

Maintaining the Readability of Promise Chains

Creating promise chains with arrays is a method I've become accustomed to. It's quite simple to follow along a chain of promises when each one fits neatly on its own line like so: myArray.map(x => convertX) .filter() .whatever() .etc() ...

The props in Vue 3 are not functioning as expected in child components even after being bound correctly, resulting in undefined values in the child component

Exploring the realms of Vue and Laravel, I find myself in new territory. As the parent element, I fetch items from the database successfully. Now, the task at hand is to pass this data to the child component. <template> <div class="todoList ...