"Real-time image upload progress bar feature using JavaScript, eliminating the need for

I have successfully implemented a JavaScript function that displays picture previews and uploads them automatically on the onchange event.

Now, I am looking to add a progress bar to show the upload status. However, all the solutions I found online are related to working with submit buttons. Can someone please assist me in modifying the code? Here is the link to the question

Thank you for your help!

<input type="file" id="5_slika_upload" name="5_pocetna_slika_file" accept="image/*" />

function pocetna_slika_upload_select(){
    pocetna_slika_upload_div.style.display="flex";
    var reader = new FileReader();
    reader.onload = function() {
        var output = pocetna_slika_upload_div_img;
        output.src = reader.result;
    }
    reader.readAsDataURL(event.target.files[0]);
    
    var file_data = $('#5_slika_upload').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    $.ajax({
            url: "https://markolucic.from.hr/image_upload.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
        
    //implementation of progress bar goes here...
        
}

Answer №1

To implement a progress bar for file uploads, utilize the xhr parameter within a $.ajax call to set up an upload progress event handler.

$.ajax({
        url: "https://uniquewebsite.com/upload.php",
        type: "POST",
        data: form_data,
        contentType: false,
        cache: false,
        processData:false,
        xhr:function(){
            var xhr = new XMLHttpRequest();
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percentComplete = (e.loaded / e.total) * 100;
                    console.log(percentComplete);
                }
            };                
            return xhr;
        },
        success: function(data){
            console.log(data);
        }
    });

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

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

Challenges encountered when using random values in Tailwind CSS with React

Having trouble creating a react component that changes the width based on a parameter. I can't figure out why it's not working. function Bar() { const p =80 const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]` console.log(styl ...

Can you elaborate on the users object found in the npm registry JSON response?

When looking at the json response of any npm package, such as jQuery for example, http://registry.npmjs.org/jquery, you may come across a dictionary called users. This dictionary contains usernames as keys and boolean values as the corresponding values. ...

Arranging a javascript object by organizing an array as a value

Looking to organize a JavaScript Object structured as key:pair, where the pair consists of an array with 2 timestamp values. The goal is to arrange the elements so that those with the smallest numbers (earliest times) are shown first. For instance, consid ...

What is the best way to conceal a div when there are no visible children using AngularJS?

I need help with hiding a parent div only if all the child items are invisible. I have successfully hidden the parent when there are no children, but I am struggling to figure out how to hide it based on visibility. <div ng-repeat="group in section.gro ...

List of items displayed in alphabetical order using the ng-repeat directive:-

I'm working with an ng-repeat block in the code snippet below. My goal is to have the placeholder [[THE ALPHABET]] render as a, b, c, d representing bullets for the list in their respective order. There will always be 4 values present. What would be t ...

Having trouble updating text in a PDF using NodeJS and hummus library

How can NodeJS be used to replace a string in a PDF file? offers a solution for text replacement in a PDF document. However, when applying the same code, an issue arises where the replaced text is visible in the source code of the PDF but does not render p ...

Using Perl to pass query information with ajax/json and including scalar reference for DBIx::Class

I am currently facing an issue while trying to pass a query from jquery/ajax/json to a perl script that utilizes DBIx::Class and returns the results. While I have no trouble getting a basic query to function, I encounter difficulties when needing to includ ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

Codeigniter's Force Download feature is malfunctioning

I am attempting to use force_download in Codeigniter to download a file. To achieve this, I have created an AJAX call as shown below: $.ajax({ type: 'POST' , url: '<?php echo base_url('downloadPayroll'); ?>' ...

JavaScript for varying content that is dynamically loaded on a completely ajax-powered website

This post has been updated to address the issue more effectively with a refined concept and code (based on the responses provided so far) I am working on developing an ajax-driven website, but I have encountered some issues with multiple bound events. He ...

Need to remove bold formatting? Try this compact WYSIWYG editor!

Hello Stack Overflow community, I discovered a method called str.bold() that wraps text in <b></b> tags, which is perfect for a small WYSIWYG editor (I understand there are many open source solutions available, but I wanted to learn by creatin ...

The issue of empty strings not converting to null when passing a JSON object to a controller

My observation in ASP.NET Core 2.1 is quite the opposite of a similar question raised about string.empty being converted to null when passing JSON object to MVC Controller. In my case, when a JSON object with properties containing empty strings is sent ba ...

What is the button that switches the bootstrap modal?

With my bootstrap modal form, I have multiple buttons that trigger it as shown below: <a href="javascript:void(0)" data-toggle="modal" data-target="#specialoffer"> <button class="green full" id="button1">Ask Question</button> </a& ...

Tips on showing database information with JavaScript

<script type="text/javascript"> var content = { metadata: ['January', 'February', 'March', 'April'], infoSets: [ { fillColor: "rgba(220,220,220,0.2)", strokeCol ...

Conceal two DIV elements if one of them is empty

My slideshow has thumbnails connected to each slide. There are 10 DIVs representing the slides like this... <div class="SSSlide clip_frame grpelem slide" id="u751"><!-- image --> <?php while ($row = mysql_fetch_array($query ...

When redirecting to the same component, Vue.js hooks are not triggered

In my Vuejs project, I have two pages located at the same level with a common component. However, when I redirect from post/new to post/edit/:id, the beforeMount method is not being called. redirect() { this.$router.push({path: `home/post/edit/${this ...

unable to retrieve JSON sub-elements

I encountered an issue while attempting to iterate through the JSON object provided. When trying to access the content-items using page.content-items, I received an error message. Is it possible to access an object that has a key with "-" in its name? Co ...

Form that adjusts input fields according to the selected input value

I am in need of creating a dynamic web form where users can select a category and based on their selection, new input fields will appear. I believe this involves using JavaScript, but my searches on GitHub and Stack Overflow have not yielded a suitable sol ...

including a close button when in use and excluding it when not in use

Seeking assistance with removing the "close" icon if it is not active. Here is the code I currently have $("#mason2 li div").click(function() { $(this).parent().hide().appendTo("#mason2").fadeIn(200); $(this).append('<p class="close"& ...