Utilize AJAX to seamlessly upload files alongside pre-existing form data

I'm currently using Vue JS to save a form with ajax and post the data.

var data = JSON.stringify(vm.data);

I want to include file uploads in the same request. I have come across examples using FormData, but none show how to add files while still posting the existing data together in one request.

I know that individual fields can be added using formData.append(name, value);, but this only handles one value at a time. The data object I am sending is an array of objects and includes child objects as well.

Is there a way to append the entire data object at once, or do I need to iterate through each item and append them individually?

EDIT - Current ajax request:

var data = JSON.stringify(vm.data);

me.xhr({
    headers: {'Content-Type': 'multipart/form-data'},
    method: 'PUT',
    url: 'swatch/' + vm.swatch.id + '.json',
    callback: function(res) {
        vm.saving = false;
        try {
            alert(res.message ? res.message : "Swatch saved successfully");
        } catch (e) {
            alert(res.message ? res.message : "Failed to save the changes, please try again.");
        }
    },
    onerror: () => {
        vm.saving = false;
        alert('Failed to save the changes, please try again.');
    },
    data: { swatch: data }
}

Answer №1

Utilizing FormData for:

let data = JSON.stringify(vm.data);
let fd = new FormData();
fd.append('data', data);
fd.append('file', vm.fileUploaded);

me.xhr({
headers: {'Content-Type': 'multipart/form-data'},
method: 'PUT',
url: 'swatch/' + vm.swatch.id + '.json',
callback: function(res) {
    vm.saving = false;
    try {
        alert(res.message ? res.message : "Swatch saved successfully");
    } catch (e) {
        alert(res.message ? res.message : "Failed to save the changes, please try again.");
    }
},
onerror: () => {
    vm.saving = false;
    alert('Failed to save the changes, please try again.');
},
data: fd
}

Integrating into component:

<input type="file" @onchange="changed($event)">

new vue({
data:{ fileUploaded:'' },
  methods:{
      changed(event){
          this.fileUploaded = event.target.files[0];
       }
   }
})

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

We are currently experiencing issues with Internet Explorer retrieving data from input type text

My HTML code includes input elements with type="text" like this: <input type="text" class="f_taskname" value=""/> Once the user enters text and hits enter, the following script is triggered: var task_name=$('#filter_body').find('.f_ ...

From gathering user input on an HTML form, processing it using PHP, storing the data in a MySQL database, retrieving it with PHP, converting it to JSON

Description of issue: I am attempting to retrieve a value from an HTML input using PHP and execute a query on a MySQL database: SELECT * FROM WHERE (value = ID in the HTML input). MY APPROACH: I have created an HTML input: <input id="akt_djubrenje" ...

Tips for fixing the issue of "The use of getPreventDefault() is outdated. Please use defaultPrevented instead."

When attempting to fetch data for a specific user from an SQL Server database using JSON data, I encountered an error message in the console: "Use of getPreventDefault() is deprecated. Use defaultPrevented instead." Additionally, the values are not bei ...

Having trouble with React testing-library: Why is the file upload empty when testing a PDF file?

While testing file upload with react-testing-library, I encountered an issue where the log indicated that the file was empty (even though it worked in the browser). After researching various docs and bugs, I discovered that since tests run on Node.js, the ...

Can somebody please tell me the equivalent of the sleep() function in JavaScript?

Are there more efficient ways to implement a sleep function in JavaScript compared to the pausecomp function as shown below (sourced from here)? function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); ...

Break down the string and iterate through using AngularJS

When looking at a string in the format "Something for example $takeThis $takeThisAlso", I need to parse it and extract all substrings that are enclosed within $ ($xxx). This means I want to achieve something like this: foreach($xxx in list) { var field ...

Deciphering jQuery serialized information in C#

I'm working with a ListBox on my webpage and trying to send the selected values through an AJAX call to a C# function. Here's what I currently have in place: $('#btnSubmit').click(function() { $.ajax({ type: "POST", ...

What is the best way to incorporate a BigDecimal from Scala.js into my JavaScript project?

Presented below is an example of a Scala object: @JSExportTopLevel("Calculator") object Calculator { @JSExport def calculate(): BigDecimal = 3.14 } The exported singleton method can be invoked from a JavaScript application, but the result m ...

Guaranteeing the sequential execution of JavaScript functions

For weeks, I've been struggling with a program that utilizes ajax post methods and dataTables. It has become clear to me that my understanding of how javascript operates is lacking. Below is the javascript code: $('#SaveTimeSheet').click(fu ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

Challenges with Struts2 Ajax implementation

Here's the issue: When a user clicks on the link, I load the data into a div. However, if the user's session expires or there is an external error, I need to redirect them either to the login page or an error page. The current problem is that whe ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

Implementing an input field using JavaScript

I have multiple search forms, each containing an input field with the class "search_input". My goal is to add the following code on button click: <input type="submit" class="searchbtn" value="Search" /> next to each input <input type="text" cl ...

What could be causing my randomly generated value to be overwritten so quickly?

I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall(), getRandomIntX(), and getRandomIntY(). However, the random value seems to be constantly overwritten. How can I resolve this problem? ...

Tips for removing parameters from rendered XML in Grails

My current challenge involves a specific class: class Category { String name SortedSet items static hasMany = [items:Item] } When it comes to rendering this category as XML in the controller, I am facing an issue: def getCategory = { rende ...

Retrieving the chosen date from a calendar using a jQuery function

Hey there, I need help with showing tasks created on a specific date by selecting that date from a full month calendar. https://i.sstatic.net/hbLtp.jpg There are multiple tasks created on the selected date, and I want to trigger a jQuery event to fetch d ...

Can you identify the HTML table format and suggest effective web scraping methods?

I have been attempting to retrieve data from the following link, http://www.rchsd.org/doctors/index.htm? strt = 0 & ln = & fn = & sp = & grp = & loc = & lng = & gen = , using R but finding it quite challenging. I have observed that the URL remains constan ...

Scope problem leading to variable being returned as undefined

Having some trouble with fetching youtube videos for the data I scraped from officialcharts.com. Even though I can scrape the data and obtain the youtube URLs, the variable youtubeUrl is not being assigned a value when I try to push the data into the array ...

Clicking outside the box will close it

I received a code from the internet that allows me to click on text and open a box. However, I am looking to add functionality to close the box when I click outside of it. Here is the javascript code I am using: function setVisibility(id, visibility) { ...

Looking for a solution to the issue below? A pesky JavaScript/Ajax dilemma is causing trouble

Hey there! I'm currently working on an ASP.NET Core application that utilizes AJAX and a login.js file to send data to my API. However, when trying to execute JSON.stringify(formData) in the browser, I encounter the error message: Uncaught ReferenceEr ...