Why isn't my redirection functioning properly?

My code is having an issue with the redirect function being called too early, causing the last file of a batch upload to fail. I've been searching all morning and trying different solutions without success.

function uploadFile(something, callback) {



    var fileInput = $('#fileList1');
    //var reader = new FileReader();
    console.log(fileInput);
    if ( trim( fileInput.val() ).length == 0 ) {
        return;
    }
    var fileList = []; 
    count = fileInput[0].files.length; 
    for(i = 0; i < count; i++){

        loadFile(fileInput[0].files[i]);

    }

    function loadFile(file){

        var reader = new FileReader(); 
        var fileName = getFileNameWithExtension( file);
        var file = file;
        while(reader.onprogress){
            console.log("reading");    
        }

        reader.onload = function(event) {
            var val = reader.result; 
            var text = val.split(',')[1];
            saveFile( fileName, text, parentId );
            if (!--count){
                redirect();                    
            }

        }

        reader.onerror = function(event) {
            console.error("File could not be read! Code " + reader.error.message);
        }
        reader.readAsDataURL(file);

    }

}
function redirect(){

    window.location.href = '/{!tempID}';
    return false;
}

Any ideas on what might be causing this issue?

#

Hello, I've made some adjustments to my methods based on your suggestions. However, the redirect is still happening too early, before all uploads are complete.

function uploadFile() {


    var fileInput = $('#fileList1');

    console.log(fileInput);
    if ( trim( fileInput.val() ).length == 0 ) {
        return;
    }
    var countTwo = 0; 
    count = fileInput[0].files.length; 
    for(var i = 0; i < count; i++){

        loadFile(fileInput[0].files[i], function(val){
            console.log(val);
            if(val === 3){
                setTimeout(()=>{redirect();}, 5000);
            }

        });
    }

    function loadFile(file, callback){

        var reader = new FileReader(); 
        var fileName = getFileNameWithExtension( file);
        var file = file;
        while(reader.onprogress){
            console.log("reading");    
        }

        reader.onload = function(event) {
            var val = reader.result; 
            var text = val.split(',')[1];
            saveFile( fileName, text, parentId );
            console.log(" ct " + countTwo + " c " + count-1);
            countTwo++;

            if(!--count) callback(countTwo);

        }

        reader.onerror = function(event) {
            console.error("File could not be read! Code " + reader.error.message);
        }
        reader.readAsDataURL(file);

    }

}

Answer №1

Option 1: (Highly Suggested)

Monitor the completion of your upload process and trigger a redirect in the callback.

Option 2:

// set TIMEOUT value beforehand
setTimeout(()=>{redirect();}, TIMEOUT);

Answer №2

When the reader finishes loading, it triggers a function that retrieves the result and splits it to extract the text part. This text is then passed to a function along with other parameters like the file name and parent ID. If the count variable decrements to zero after this operation, a redirect function is called with a slight delay.

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

Utilizing Node.js and Node-Postgres: Organizing Database Queries in Models

In order to enhance the efficiency of my code, I am looking to modularize my queries by organizing them into functions with appropriate names for their tasks. Instead of cluttering up the req, res functions (controllers), I aim to encapsulate them in a se ...

How can I retrieve the number of links pointing to a specific property within a JavaScript object

I am faced with the following dataset: const main = 'test1'; const data = [ { from: 'test1', to: 'test2' }, { from: 'test2', to: 'test3' }, { from: 'test3', to: ...

Why does this function properly on every browser except for Opera?

I have implemented a script that allows me to replace the standard file upload input with a custom image. The script also ensures that an invisible 'browse' button appears underneath the mouse pointer whenever it hovers over the custom image. Thi ...

for each item, assign a unique ink color

Hello there! Currently, I am working on a straightforward online shopping MVC application. Within this application, there is a table containing three categories: Laptops, Mobiles, and Consoles. I have created a partial view that fetches these categories fr ...

What steps are needed to create a transport directly from the Console?

In my current setup, this is the code I have: const logger = new winston.Logger(); logger.add(winston.transports.Console, { level: environment === 'development' ? 'silly' : 'info', colorize: true, prettyPrint: true }); ...

How can we monitor the value of $route.params.someKey in Nuxt.js?

When working with Nuxt.js, I am trying to keep track of the value associated with a key called key1 in the $route.params. The values for key1 are determined using a function called someFunction(). Is there a way for me to monitor $route.params.key1 as a ...

Embed JavaScript code in the head section of the webpage to guarantee its presence even following a page refresh

We recently obtained an innovative Enterprise Talent Management Solution that is cloud-based. One standout feature allows users to incorporate HTML Widgets with scripts on the primary Welcome Page. The customization options for the Welcome Page UI are qui ...

Is there a way for me to retrieve the name of a newly opened browser tab from the original tab?

I have written a code snippet to create a new tab within the same browser by clicking on a link. function newTab() { var form1 = document.createElement("form"); form1.id = "newTab1" form1.method = "GET"; form1.action = "domainname"; //My ...

JavaScript code to enforce a 100% page zoom setting

After developing a small game in Canvas, I encountered an issue. Some users with their default zoom level set to something other than 100% are unable to view the entire game page. I attempted to resolve this by using the following CSS: zoom: 100%; This ...

Adding an item to a nested array within an object in a Redux reducer

Here is an example of my initial state: let initialState = { data: { name: 'john', books: [ { name: 'a', price: 220 } ] } } Is there ...

Using AJAX to dynamically update text areas on a webpage without the need to refresh the

My goal is to dynamically update the content of a textarea on my webpage when a form is submitted, without having to refresh the entire page. Initially, I attempted to achieve this using AJAX with the following code: $("#db_info").load(document.location.h ...

Ways to develop tests for functions specific to my scenario

Currently, I am attempting to implement a timeout function test within my application. Within the controller: $scope.$watch('toy',function(toyVar){ if(toyVar == 1) { //perform actions } else { $timeout(f ...

Using JavaScript, generate ten clickable circles on the screen. Each circle should display the number of times it has been clicked in the center when interacted with

I am currently working on my JavaScript skills and would like to implement a fun project involving 10 colorful circles. While I can easily create these circles using HTML and CSS, I require assistance with the interactive functionality using JavaScript. ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

Can an HTML DOM object be converted to a JSON string using JSON.stringify in JavaScript?

Trying to fetch an external HTML file and convert its body content into a string has been giving me unexpected results. Is there a way to achieve this successfully? var xhr = new XMLHttpRequest(); function loadFile(){ xhr.open("GET", 'index.html ...

How can Conditional Rendering be applied within List Rendering (v-for) in Vue JS?

In my current project, I am utilizing List Rendering (v-for) to display information about various books stored in an array. One challenge I'm facing is implementing conditional rendering within this loop to dynamically generate li elements that repre ...

What is the technique to make a *ngFor render items in a random order?

I'm working on creating an application that needs to display elements in a random order. However, due to restrictions within the application, I am unable to modify the ngFor directive. How can I achieve displaying ngFor content randomly? ...

Issue with SweetAlert2 cancel button being unresponsive while an ajax request is in progress

I have a custom function triggered when a dropdown item is selected, which triggers a sweetalert2 popup. Here's the function: function SwalPopup(ip, method) { var methodmsg = method.charAt(0).toUpperCase() + method.slice(1); swal.fire({ ...

Running into difficulties while attempting to sort through an object utilizing an array

My task is to filter a collection of objects based on an array of Fids. I have an object, $target = $('#tableA tr[data-id="' + elm.id + '"]'); // Collection of tr And I also have an array, var fids = $("#tableB tr .New.selected").pa ...

Ways to determine the total number of pages in a PDF using a stream

Utilizing a library such as pdf-parse enables us to extract the number of pages (numpages) from a PDF buffer. The challenge I am facing is handling large buffers that cannot be stored in memory, prompting me to consider streaming it instead: const response ...