Sending a request for the second time may result in data duplication

To upload a file to the server, I use the following code snippet:

var fd = new FormData();
fd.append('folder', 'html');
fd.append('permission', 0);
fd.append("file", file, file.name);

After selecting the file from an input field, my request is as follows:

$.ajax({
                     type: "POST",
                      url: getURI("fileupload"),
                      success: function (data) {
                          reader.onload = function (e) {
                              callback(data.body.url, {
                                  alt: ''
                              });
                          };
                          reader.readAsDataURL(file);
                      },
                      error: function (error) {
                          // handle error
                      },
                      async: true,
                      data: fd,
                      cache: false,
                      contentType: false,
                      processData: false,
                      timeout: 60000
                  });

1) Uploading the initial file works fine. 2) When trying to upload a second file, it does upload successfully, but there seems to be an issue with the FormData - when attempting to send multiple files, only the last one gets sent while the others are still being attempted.

Is there a way to remove previous FormData entries?

Answer №1

$.ajax({
    type: "POST",
    url: getURI("fileupload"),
    success: function (data) {
        reader.onload = function (e) {
            callback(data.body.url, {
                alt: ''
            });
        };
        reader.readAsDataURL(file);

        //
        // Make sure to clear the file input at this point
        //
    },
    error: function (error) {
        // handle error
    },
    async: true,
    data: fd,
    cache: false,
    contentType: false,
    processData: false,
    timeout: 60000
});

In the success callback, it is important to manually clear your file input. For more details, refer to this resource

After that, initialize a new FormData instance named fd:

fd = new FormData();

For further information on clearing FormData objects, visit this link

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

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

How can you enable fullscreen for a featherlight iFrame?

I have implemented Featherlight to display an iframe within a popup modal on my website. If you click the iframe button, you can see a demo of how it works. One issue I am facing is that the generated iframe tag by Featherlight does not include allowfulls ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Adding numerous objects to a Vuex store using mutations

I am currently working with the following store setup: import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ plugins: [createPersistedState()], state: { ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

Tips for creating a secure authentication system in an AngularJS application!

As a novice in the world of angularjs... After going through the documentation and completing a tutorial, I decided to experiment on my own which has helped me grasp things better. Now, I'm looking into creating a secure authentication system. The ...

Error: Cannot access 'addEventListener' property of null in Chrome Extension due to TypeError

I've been working on developing a chrome extension that autofills input forms in web pages. However, I encountered an error that says "cannot read properties of null." This issue arises when I try to add an event listener to a button in my code. The f ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

When an identical Ajax request is made multiple times, Safari will block JQuery

I'm having trouble getting my progress bar to update in Safari (8.0). While uploading a file, the progress bar updates automatically in Firefox and Chrome, but not in Safari. I suspect this may be due to Safari not handling synchronous events, causing ...

What is the optimal method for assigning a value to a specific key within a JavaScript JSON object?

Below is the information stored in a file called "fokontanys.json": { "vzdveg643": { "lldistrict":"Ambilobe", "id_province": 7, "id": null }, "vzvsdv5327": { "lldistrict ...

What steps can be taken to ensure that any new elements generated by JavaScript do not disappear upon refreshing the page

I am currently working on a project where I am creating a list by collecting user information and storing it in a MySQL database. When the user clicks the 'add' button, a new element is added to the bottom of the existing list which is coded in H ...

Is there a way to make my code on Google Sheets work across multiple tabs?

My Google Sheets code successfully pulls information from the main tab into my CRM Software every time someone fills out a form online. However, I'm struggling to get the script to run for multiple tabs on the same spreadsheet. I've tried a few s ...

Node.js Multer encountering undefined req.file issue when handling multiple file uploads

FIXED: ( NO req.file ) ( YES req.files ) My project requires the ability to upload multiple files. If single image uploads are working but multiple image uploads aren't (uploading to files), I need req.file.filename in order to write the image path ...

Having trouble loading the DOM element within the child component

An issue has arisen with Angular 4.4.6 regarding the access of a DOM element by ID from a different component. Within my component, I aim to display a Google Maps for specific purposes. Following the examples given in the API, I include the following code ...

Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated. This is the code in my middleware.ts file: import { NextResponse } from 'next/server' im ...

Dilemma arises from conflicting javascript codes

Currently, I am developing a web application where the main page features a timeline that needs to update its content automatically. To achieve this, I am utilizing the setTimeOut function of JQuery to refresh the timeline every x seconds. In addition, th ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

Use JavaScript to swap out images

How can I change the image arrow when it is clicked? Currently, I have this code snippet: http://codepen.io/anon/pen/qEMLxq. However, when the image is clicked, it changes but does not hide. <a id="Boton1" class="button" onClick="showHide()" href="j ...

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...