Transmitting occasional feedback from ASP.NET Web API function to jQuery AJAX

I am currently working on a project that requires sending intermittent status responses from a Web API method back to a jQuery AJAX call in order to display progress in the UI.

https://i.sstatic.net/Y6R4w.png

The process involves the jQuery AJAX calling the Web API method with specific parameters, initiating long-running actions. After each action completes, I aim to send a manually inputted percentage back to the AJAX call and update the UI with the progress.

Here is what I have attempted so far:

HTML:

<div class="row">
        <div class="col-xs-12">
            <div class="col-xs-3">
                <input type="file" id="FileInput" />
            </div>
            <div class="col-xs-1">
                <button type="button" class="btn btn-default btn-xs" id="UploadFileBtn">Upload</button>
            </div>
        </div>
    </div>

Typescript:

        instance.importFile.on('change', function () {
            instance.selectedFile = this.files[0];
            // This code is only for demo ... (usage of FileAPI)
            console.log("name : " + instance.selectedFile.name);
            console.log("size : " + instance.selectedFile.size);
            console.log("type : " + instance.selectedFile.type);
            console.log("date : " + instance.selectedFile.lastModifiedDate);
        });

        $('#UploadFileBtn').on('click', function () {
            var formData = new FormData();
            formData.append('file', instance.selectedFile);

            $.when(FileUploadService.ProcessData(formData)).done(function () {
            }).fail(function () {
                }).progress(function () {
                    console.log("progressing...");
            });
        });

Web API:

public class FileUploadController : ApiController
    {
    [HttpPost]
    public HttpResponseMessage Upload()
    {

        if (HttpContext.Current.Request.Files.Count > 0)
        {
            var postedFile = HttpContext.Current.Request.Files[0];

            var fileNameParts = postedFile.FileName.Split('\\');
            var fileName = fileNameParts[fileNameParts.Length - 1];

            fileName = string.Format("{0}_{1}", DateTime.Now.Ticks.ToString(), fileName);
            string filePath = Path.Combine("c:\\temp", fileName);
            postedFile.SaveAs(filePath);
        }

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent("UPLOADED");

        System.Threading.Thread.Sleep(5000);

        return response;
    }
}

Question

I have successfully created the Web API method but now I am unsure how to send intermittent responses back to the UI. I am seeking simple solutions and welcome any suggestions or examples. Thank you for your help!

Answer №1

After incorporating suggestions from Jason, I successfully implemented polling by making a separate ajax call to retrieve intermittent responses.

The following code snippet showcases my attempt to upload a file (using the jQuery.form plugin) to a server and execute long-running tasks at the controller level. To keep users informed about progress, I utilized the polling concept to monitor the status of these lengthy operations.

Below is the code snippet for reference:

ASP.NET HTML:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="row">
        <div class="col-xs-12">
            <div class="alert alert-warning">This page uses jquery.form plugin to upload</div>
        </div>
    </div>
</asp:Content>
...
...

Output:

The user interface displays the progress as depicted below:

https://i.sstatic.net/f3S1b.png

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

Error TS2345: The argument provided, which is of type 'Promise<ReadonlyArray<Object>>', cannot be assigned to a parameter that must be of type 'T | PromiseLike<T> | undefined'

My goal is to return the ReadonlyArray<> in my promise so that I can send it back to the original method that called 'dispatchToThisProcess'. This abstraction allows for potential future updates to multiple processes. Below is the code snip ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...

Tips for utilizing variables as the initial value of a JSON Object

Here is a JSON configuration example: { "Users" : { "182723618273612" : 15, "AddedUser" : 1 } } I have generated this field using a JavaScript function, but now I want to change the name of "AddedUser" ...

I am having issues with the Load More Posts Ajax Button on my WordPress site and it is

I'm trying to display more posts when a button is clicked. Upon inspecting and checking the network, everything seems to be working fine, or at least that's what I assume. https://i.sstatic.net/44VS1.jpg https://i.sstatic.net/KEkiz.jpg I&apos ...

Changing a single image within a v-for loop of images in Vue

I am currently working with an array in Vue where I am using v-for to create 3 columns of information. Each column includes an image, and I would like to be able to change only the specific image that is being hovered over without affecting any others. How ...

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

Learn how to dynamically pass a value from a prop to a router-link in Vue.js

I created a custom button component and decided to switch from using <a> tags to <router-link>. However, I encountered an error because the router-link was rendering before the prop received its value. To address this, I added an if statement b ...

Struggling to properly implement an "Errors" Object in the state function of a React Login Form Component

The issue arose while I was following a React tutorial. My objective is to develop a basic social media web application using Firebase, React, MaterialUI, and more. I am currently at around the 5:40:00 mark and have successfully resolved all previous pro ...

Using makeStyles() in MUI for conditional rendering

Trying to dynamically change the value of backgroundColor under the property "& + $track" using props.disabled but it seems that MUI does not recognize it. Why could that be? const useStyles = makeStyles((theme) => ({ root: { overflow: "vis ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa. Everything is working smoothly except for one instan ...

Perform a function on Angular 5

In my database, there is a table named settings. I have 2 backend endpoints: one for getting settings and another for updating settings. Now I am working on creating an Angular window to edit this table. I've set up an Angular Service to retrieve va ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

I'm baffled by the unexpected result I'm getting when using 'foreach' in node.js

Recently delving into node.js, I've encountered a puzzling issue. I'm perplexed as to why my output appears as: ciao data data instead of: data data ciao Below is the code causing this unexpected output: fs.readdir("sender", (err, fil ...

Exploring Angular modules has shed light on a certain behavior that has left me puzzled - specifically, when diving into JavaScript code that includes the

I am currently working with angularjs version 1.4.3 and I find myself puzzled by a certain segment of code in the Jasmine Spec Runner that has been generated. Upon generation, Jasmine (using ChutzPath) creates this particular piece of code: (function ...

Is there a way to make changes to a pre-uploaded PDF document?

I'm looking to include a footer in a PDF file that is currently stored on the server. For instance, I have uploaded a file to uploads/aaa.pdf and now I need to insert a footer into the same file located at uploads/aaa.pdf Does anyone know how I can ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

A step-by-step guide on changing an image

Is it possible to change an image when the user clicks on a link to expand its content? <ul class="accor"> <li> Item 1 <img src="../plus.png"> <p> Lorem ipsum dolor sit amet</p> </li> </ul> $(' ...

Tips for making a property non-nullable in Typescript

The Node built-in IncomingMessage type from DefinitelyTyped's definition (used as req in the (req, res, next) arguments) has specified that url can be nullable. This excerpt shows part of the definition: // @types/node/index.d.ts declare module "http ...