submit multiple images simultaneously

I'm attempting to upload multiple photos simultaneously using XMLHttpRequest.

if(files.length <= 6) {   

    for(var i = 0; i < files.length; i++)   {

      var formData = new FormData();
      formData.append('action', 'uploadPhoto');
      formData.append('photo_id', id);
      formData.append('file'+id, files[i]);
      UploadFile(formData, id);   
    } 

}

function UploadFile(formData, id)  {   

var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploadPhoto.php', false);   
xhr.onload = function (){};   

xhr.send(formData); }

The issue here is that the photo upload process gets repeated. This may be due to the loop continuing before the previous photo has finished uploading.

Answer №1

Based on the input provided, it seems like your id needs to be a unique random number for each iteration. Currently, you have set it outside of the for loop, causing it to be overwritten with a new value in each iteration. This results in only one file being uploaded as the same ID is getting reused. To avoid this issue and ensure uniqueness, I suggest using a timestamp-based approach.

Instead of generating random IDs, you can use timestamps which will always be unique at the time of generation. Here's an updated code snippet implementing this concept:

if(files.length <= 6) {   

for(var i = 0; i < files.length; i++)   {

  var id = Date().getTime();
  var formData = new FormData();
  formData.append('action', 'uploadPhoto');
  formData.append('photo_id', id);
  formData.append('file'+id, files[i]);
  UploadFile(formData, id);   } 

}
 function UploadFile(formData, id)  {   

 var xhr = new XMLHttpRequest();
 xhr.open('POST', 'uploadPhoto.php', false);   
 xhr.onload = function (){};   

xhr.send(formData); }

Answer №2

Ensure to call the uploadPhoto() function outside of the for loop rather than at the end of each iteration. Additionally, move the declaration of FormData outside of the loop.

I have also adjusted the "photo_id" parameter to include the loop counter value, providing a unique key for each file.

Moreover, I updated the last parameter of the xhr.open call to be set as "false" instead of "true" to make the xhr request asynchronous, which is generally preferred over synchronous calls.

Furthermore, I removed the id parameter from the uploadPhoto function since it was not being utilized.

It is also recommended to start function names with a lowercase letter unless they are constructor functions. Therefore, your code snippet should reflect this convention:

if(files.length <= 6) {   
    var formData = new FormData();

    for(var i = 0; i < files.length; i++)   {
      var id = getUuid();

      formData.append('action', 'uploadPhoto');
      formData.append('photo_' + i + "_id", id);
      formData.append('file'+id, files[i]);
    } 

    uploadFile(formData);   
}

function uploadFile(formData)  {   
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'uploadPhoto.php', false);   
    xhr.send(formData); 
}

function getUuid() {
   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
   });
}

The getUuid function implementation can be found at , generating a version 4 UUID.

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

Issues with a jQuery ajax request

Recently delving into jQuery and finding it enjoyable so far. However, I've encountered an issue with an ajax call and could use some assistance. Here's the code snippet for my ajax call: // Initiating the ajax request $.ajax({ // PH ...

Waiting for completion of all nested AJAX and each calls in jQuery

I am facing an issue with my JavaScript code where a particular section is not running to completion before moving on. The problem lies within nested each loops inside ajax calls, causing delays in execution. Whenever I test this in Chrome and set a break ...

The map function is mistakenly returning double the amount of the object it should be returning

My program is fetching data from an API, but when I try to map the array for interesting data, it downloads the same object multiple times. For the first search, it downloads the object twice and for subsequent searches, it downloads the object six times. ...

Encountering a Firebase error: createUser failed due to missing "password" key in the first argument in AngularJS

Recently, I started learning Angular and decided to follow an online tutorial on creating a chat application. However, I encountered an issue when trying to register with an email and password - the error message "Firebase.createUser failed: First argument ...

Determine the domain for a POST method request

Is there a way to determine the domain of another website when receiving a POST request from it? For example, if helloworld.com sends a POST request to mywebsite.com, how can mywebsite.com identify that the request is coming from helloworld.com? I have a ...

Tips for avoiding the default rendering of Nuxt 3 layout?

After reviewing the Nuxt 3 documentation and finding it lacking in explanation, I turned to the Nuxt 2 docs. According to them, the default layout should be replaced by a specific layout specified within the name property of the <nuxt-layout> compone ...

Component not being returned by function following form submission in React

After spending a few weeks diving into React, I decided to create a react app that presents a form. The goal is for the user to input information and generate a madlib sentence upon submission. However, I am facing an issue where the GenerateMadlib compone ...

Encountered an Unhandled Runtime Error in NextJs: Invalid Element Type

Attempting to build an Instagram clone following a YouTube tutorial from a year ago has led to various errors arising from nextjs14. I have managed to resolve all of them except for one particular issue: Error: Element type is invalid - expected a string ...

When attempting to retrieve information from a local database using Django and Ajax by sending parameters to URLs, a 404 error is encountered

Currently, I am striving to retrieve data from my local database utilizing Django and Ajax. I have established a view that enables users to access data while also passing arguments to filter the information. These arguments include start date, end date, an ...

Incorrect interpretation of JavaScript object

To display some structured data on my JADE page, I created a JSON-like object containing variables, text, and JavaScript objects. Here is an example of what the JSON object looks like: var dataSet1 = { meta: { "name": "Some text", "minimum": mini_ ...

Having trouble with the href attribute not properly redirecting to a different page

I am trying to create a hyperlink for an option that will take users to another page. All the other options on the page lead to different sections within the same page. When I add CONTACT, it doesn't work. All the files are in the same ...

Showing hidden errors in specific browsers via JavaScript

I was struggling to make the code work on certain browsers. The code you see in the resource URL below has been a collection of work-around codes to get it functioning, especially for Android browsers and Windows 8. It might be a bit sketchy as a result. ...

Ensuring all ajax calls have completed before proceeding using selenium webdriverjs

In my attempt to create a function that can wait for all active (jQuery) ajax calls to complete in a Selenium WebdriverJS test environment, I am faced with challenges. My current approach involves integrating the following components: Implementing WebDri ...

Guide to switching classes with jquery

On my webpage, I have a star rating system that I want to toggle between "fa fa-star" and "fa fa-star checked" classes. I found some information on how to do this here: Javascript/Jquery to change class onclick? However, when I tried to implement it, it di ...

Is there a way to make a selected option stay selected in vue.js 2?

Here is the structure of my Vue component : <template> <select class="form-control" v-model="selected" :required @change="changeLocation"> <option :selected>Choose Province</option> <option v-for="option in o ...

Ways to mimic an Angular directive with a required field

Recently, I encountered a challenge that involves two directives: directive-a, directive-b. The issue arises because directive-b has a `require: '^directive-a' field, which complicates unit testing. In my unit tests, I used to compile the direc ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

What could be causing my Puppeteer scraper to malfunction when I alter the search term?

The Task In this project, I am building a web scraper using NodeJS with Puppeteer. The goal is to scrape data for "Jeep Wranglers" and organize the results in JSON format. Comparing IPhone X and Jeep Wrangler Initially, everything worked smooth ...

When the button is clicked, the image vanishes into thin

One common issue is the image disappearing when users click on the Rotate Anti-clockwise or Rotate Clockwise buttons. This can be a frustrating problem to tackle! Check out this link for more information. If you run into this issue, here are some tips: ...

"Exploring the power of NodeJS with createServer, dealing with

Can instances of global.request potentially collide in this NodeJS scenario? I have a basic web server set up in NodeJS where I am globally exposing the request that is created: http.createServer(function(req, res) { global.request = req; // do ...