"Track the upload progress of your file with a visual progress

I have written this code for uploading files using Ajax and PHP, and I am looking to incorporate a progress bar to indicate the percentage of the upload.

Here is the code snippet:

<script>
   $("form#data").submit(function(){
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: "functions/video.php",
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            document.getElementById("status").innerHTML = data;
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false;
});
</script>
<form id="data" method="post" enctype="multipart/form-data">
<input name="up_vid" type="file" id="up_vid"/>
<div class="upload_v_icon"></div>
<div class="video_info">
    <input type="text" name="video_title" placeholder="Video title" />
    <input type="text" name="tags" placeholder="funny,9gag,nice,crazy ..."/>
    <textarea name="description" placeholder="Description"></textarea>
    </div>
    <div class="bg_upload">
    <p>By uploading this video, you agree with our <a href="">Terms</a> of service.</p>
    <button>Begin Upload</button>
    </div>
</form>

Thank you for your attention.

Answer №1

If you have a 1px wide animated gif named "progress.gif", make sure it is available. Customize the color of this gif to match your desired progress bar color.

Update your CSS with something like the following:

.uploadBar {
   background-image:url(/images/progress.gif);
   background-position: -1px;
   background-repeat:no-repeat;
   background-size=0% 100%; width:100%;
   position: relative; overflow: hidden;
}

Add this snippet to your $.ajax(); function:

xhr: function() {
   var xhr = new window.XMLHttpRequest();
   //Upload progress
   xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
      var percentComplete = evt.loaded / evt.total;
      console.log(percentComplete);
      $('.uploadBar').css({ backgroundSize: (percentComplete*100) + '%'});
      }
   }, false);
   return xhr;
   }

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

Encountering some difficulties while setting up my development tool (specifically webpack)

I have embarked on a journey to learn modern JavaScript with the help of Webpack and Babel. As a beginner in this field, my instructor is guiding me through the principles of modern JavaScript by building an app called Forkify - a recipe application. While ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

Discover the power of sorting outcomes in a Node.js-MongoDB query by utilizing a dynamic function call

Currently, I am working on a web application in Node.js that is connected to MongoDB using the Mongo native connector. In one of my JavaScript files, I have implemented a generic method to perform "find" or "findOne" operations to fetch data from a collec ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

Can you explain the functionality of the Matrix4.multiply() method in three.js?

I am currently delving into the world of three.js and finding myself faced with a challenge. My goal is to multiply two translation matrices together in order to create a consolidated matrix that encapsulates both translations: | 1 0 0 -2 | | 1 0 0 3 | ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...

Enhancing the efficiency of nested ajax calls loop

Disclaimer: While the final result is successful, I am struggling to comprehend the sequence in which a loop of nested ajax calls operates. Essentially, I have two ajax calls that fetch data from an external API using curl GET requests. They both rely on ...

Dealing with promises in React JS JSX: Best practices

Encountering the concept of managing promises within JSX for the first time in my React JS project has been quite interesting. Below is an excerpt from my component's code: import React from 'react'; import Sodexo from './Sodexo' ...

Highcharts memory leakage issue arises when working with jQuery version 2.X

After extensive testing on my AngularJS application, I have discovered a memory leak when using Highcharts with the latest version of jQuery (2.1.4). Below are links to two plunkers for comparison: Using jQuery 1.8.2: http://plnkr.co/edit/lQ6n5Eo2wHqt35OV ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

JavaScript/jQuery countdown timer failing to initialize properly

Having some trouble with a countdown timer that I customized from the original version. The issue seems to be with startCountdown(startDate,deadlineDate,expiredText) as it's returning undefined. Any thoughts on what might be causing this? All relevan ...

Manage the lineup of tasks in the bull queue by organizing them into groups

I am currently working on a nodejs application that handles queues using the bull library. The application is required to make multiple asynchronous HTTP requests and then process the results of these calls. I'm curious about whether bull would be an ...

Is it Appropriate for Custom React Hooks to Trigger Re-Render of Related Components?

I have just developed a custom hook that internally uses useState and useEffect. After importing this hook into another React function component called ComponentA, I noticed that ComponentA re-renders every time the state within the custom hook changes. ...

Angular.js fails to load successfully every other time

My angular application is running into some issues with bower. At times, when I start up the server, I encounter the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:modulerr] Failed to in ...

Numerous Levels of Dropdown Menus

I am looking to implement a feature on a web page where users can select multiple vehicles using JQuery. The idea is that selecting the brand in the first dropdown will populate the second dropdown with the models available for that specific brand. The ...

Conditionals causing issue with React Button disabled property functionality

Having a DIV with two child elements, namely buttons that should be disabled under certain conditions. Despite correct conditions being applied, the buttons remain enabled which is causing confusion. The code snippet in question is as below : < di ...

Effectively monitoring coordinates on both the client and server sides

I'm currently in the process of developing a multiplayer game using websockets, node, and JavaScript. I need advice on the most effective approach to update client information and manage their coordinates on the server. The method I am using at the mo ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

What methods can be used to construct components using smaller foundational components as a base?

Is there a more elegant approach to constructing larger components from smaller base components that encompass common functionalities, akin to an interface in the OOP realm? I'm experimenting with this concept, but it feels somewhat inelegant. Repor ...

What is the best way to output the leaf nodes from an array of object lists in TypeScript?

Having trouble with TypeScript, specifically working with arrays and filtering out leaf nodes. I want to print only the leaf nodes in the array, resulting in ['002', '004', '007']. Can someone please assist me? Excited to lear ...