The ng-grid is failing to update with the most recent data following the asynchronous XMLHttpRequest response

I am facing an issue with my AngularJS web application. I am trying to upload a file to a server and update ng-grid with the last uploaded file's entry once the upload is complete. Below is the HTML for my grid:

<div class="gridholder" data-ng-grid="viewmodel.gridOptions">                
            </div>

Here is the logic in my controller:

vm.gridOptions = {
            data: 'gridData',            
            enableColumnResize: true,            
            enablePaging: true,
            columnDefs: [
                { field: 'FileName', displayName: 'File Name', width: 250 }
                { field: 'UploadedDate', displayName: 'Uploaded Date'}
            ],
            multiSelect: false,
            enableSorting: true,
            showFooter: true,
        };

While the upload progresses, I need to display the progress and ensure the application remains responsive. However, I am experiencing a scenario where the ng-grid does not update.

When I stay on the same page during the upload and receive the response, the grid refreshes successfully. But if I navigate away from the upload page and return after the response is received, the grid does not get updated.

Below is my file upload JavaScript code:

var data = new FormData();
data.append('file', file);
var xhrRequest = Factory.uploadFileRequest('UploadFile');
xhrRequest.upload.addEventListener("progress", progressHandler, false);                

xhrRequest.onreadystatechange = function (e) {
};

xhrRequest.onload = function (e) {
    if (JSON.parse(e.currentTarget.responseText).Success == true) {
        $timeout(function () {
            $scope.LoadGrid();
            //show success message here
        }, 2000);
    }
    else
    {
        //show error message here                    
    }

};
xhrRequest.onerror = function (e) {                    
   //show error message here                 
};
xhrRequest.send(data);

$scope.LoadGrid = function () {            
    Factory.callGet("Files").then(function (d) {
            $scope.gridData = d.data;
            $scope.totalItems = $scope.gridData.length;
        }               
    }, function error(err) {
        //Error Message
    });
}

gridData contains the value for data-ng-grid. I have already called LoadGrid method inside a $timeout, but the grid is still not refreshing with the latest data. Any assistance would be greatly appreciated.

Answer №1

Issue Alert

The problem arises when the upload logic is embedded within the controller. As AngularJS discards the controller upon switching to another view, there is no listener available to handle the file upload response.

Suggested remedy:

1) Opt for a service (or Factory) as a singleton to oversee the upload process. For instance, utilize

MyService.upload(data).then(function (response) {/**/});

2) Normally, MyService.upload(data) furnishes a promise periodically while simultaneously storing the outcome inside the Service, such as upload_results:

app.service('MyService',['$q',function ($q) {

    var self = this;

    var upload_results = [];

    self.upload = function (_data) {
        return // <YOUR_PROMISE> 
          .then(function (response) {

              upload_results.push({
                    id: new Date().getTime(), 
                    data: response.data
               })              
            }
            , function (error) {
              console.error(error);
              return $q.reject(error);
            });
      };

    self.getResults() = function(){
      return upload_results;
    }

    self.resetResults() = function(){
      upload_results = [];
    }
}

Upon initializing or revisiting the controller, check with the service if there are any pending results:

   var results = MyService.getResults();

   if(results.length > 0){
    $scope.gridData = results[0].data; // alternatively, use timestamp for organization
    MyService.resetResults();
   }

Trust this provides some clarity,

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

IE9 encounters an error when using jQuery's .remove() function

While testing my website in IE9 using Firebug Lite, I encountered an issue. When attempting to run a basic command to remove a div, I received an error saying "TypeError: Object expected". The command I used was: $("#drag-hoverbox_you").remove(); Interes ...

What is the best way to retrieve data in a controller's method using ajax?

I am attempting to asynchronously send data to a controller's method. Although I thought this would be a simple task, I was unable to find the solution on Stack Overflow. Below is my code: Controller public function actionRaiting(string $idUser, st ...

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

Exploring the power of hierarchical organization in node.js modules

One of my modules is called UserProvider and it has the following structure: var UserProvider = function(db) { ... } UserProvider.prototype.createUser = function(email, password, callback) { ... } UserProvider.prototype.findUserByEmail = function(email, c ...

I noticed a change in the state between dispatches, but I did not make any alterations to the state

Although this question has been previously raised, most of the discussions focus on the OP directly mutating the state. I have taken precautions to avoid this by using techniques like the spread operator with objects and arrays. However, despite these effo ...

What is the best way to save a large array to a .txt file in node.js?

It seems that using fs.writeFile is the obvious solution. However, after reading the response to this question, it appears that a Stream technique might be more appropriate. In an attempt to delete a line from a text file by converting it to an array, I ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Unable to generate new entries with HTML Form

I've been working on creating a simple form with the ability to add new seasons or entries that will be posted to a database, but I've hit a roadblock. Whenever I try to run it, the "Add more Episodes" buttons for new seasons don't seem to w ...

How to Query MongoDB and reference an object's properties

I'm trying to execute a script on my MongoDB that will set teacher_ids[] = [document.owner_id]. The field owner_id already exists in all the objects in the collection. Here is my current attempt: db.getCollection('readings').update({ $where ...

Steps to remove a specific child element using jQuery:

CSS: <h1><br style="clear:both;"></h1> I am currently working on a project that involves using the Wikipedia API. One issue I've run into is cleaning up the raw HTML output from Wikipedia, specifically dealing with removing a speci ...

Need help accessing data from an API using Axios.post and passing an ID?

Can someone help me with passing the ID of each item using Axios.Post in order to display its data on a single page? The image below in my Postman shows how I need to send the ID along with the request. Additionally, I have the first two URL requests for t ...

After changing the page, the Facebook JS SDK fails to function properly when using JQueryMobile

I'm facing an issue with my webapp that utilizes jQuery Mobile for full ajax navigation. I have initialized the Facebook SDK at the pageinit event in jQueryMobile (called on each page). jQuery(document).on('pageinit', function (event) { ...

npm build issues stemming from browserlist configurations

I am encountering an issue with my create-react-app failing to build, showing the following error: ./src/index.css Module build failed: BrowserslistError: Unknown browser query `dead` at Array.forEach (<anonymous>) I have carefully reviewed my ...

Can React avoid re-rendering if the setState does not impact the rendering process?

For example, let's consider a scenario where a hook is used to make an API request: function useApi(...) { const [state, setState] = useState({ fetching: false }); useEffect(() => { setState({ fetching: true }); fetch(...) .then( ...

Receive a distinct key alert after including a key attribute to a div element containing multiple sub nodes in react version 18.2.0

When attempting to render the div element on the page, I encountered a warning stating: "Each child in a list should have a unique 'key' prop." <div {...{}} key={"formKey"}> <input type="text" /> <button> ...

JSF with PrimeFaces triggers two Ajax calls when deleting and filtering data

Our application utilizes Wildfly and a JSF Primefaces version 6.2 UI. During testing, I noticed that Primefaces makes two AJAX calls when executing the following scenario: Perform filtering by name Filter by Name <h:form id="accountForm"> ...

Utilizing the HTML5 Download attribute for linking to external files

I am currently developing a web application for my own personal needs. One feature I would like to implement is the ability to set the download attribute on certain links. However, I have run into an issue where the files to be downloaded are hosted on ex ...

After refreshing the page, the initials vanish

One issue I'm facing is with a useEffect in my code. I am retrieving the name and email from my database and displaying the initials in an avatar in the header. However, after refreshing the page, the initials disappear. The commented code contains th ...

Can you provide a database of words for different cities, towns, and countries in MongoDB (or in JSON

Currently, I am in the process of developing an application that utilizes MongoDB. One specific feature I am working on implementing is an 'auto-suggest' functionality on the front-end. For example, as a user begins to type the first few letters ...

Is it possible to use a JavaScript string as a selector in jQuery?

So, my issue is with the following JavaScript code snippet: for ( i=0; i < parseInt(ids); i++){ var vst = '#'+String(img_arr[i]); var dst = '#'+String(div_arr[i]); } I'm wondering how I can proceed in jQuery to handle ...