Error: Trying to send FormData to ajax results in an Illegal Invocation TypeError being thrown

Successfully sending a file to the server for processing using the code below:

var formData = new FormData();
formData.append('file', $('#fileUpload')[0].files[0]);
options = JSON.stringify(options); // {"key": "value"}

$.ajax({
        url: "url",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {

        },
        error: function (msg) {
            showMsg("error", msg.statusText + ". Press F12 for details");
            console.log(msg);
        }
    });

However, I want to send both FormData and a json object. Attempting something like this:

var formData = new FormData();
formData.append('file', $('#fileUpload')[0].files[0]);
options = JSON.stringify(options); // {"key": "value"}

$.ajax({
        url: "url",
        type: "POST",
        data: { "formData": formData, "options": options },
        //dataType: "json",
        //processData: false,
        //contentType: false,
        success: function (data) {

        },
        error: function (msg) {
            showMsg("error", msg.statusText + ". Press F12 for details");
            console.log(msg);
        }
    });

Encountering an Uncaught TypeError Illegal invocation error message. Research suggests no examples of sending form data this way. Is there a need for restructuring or another method to send a json object with form data?

Answer №1

It is effective to attach the JSON object options to the FormData.

var formData = new FormData();
formData.append('file', $('#fileUpload')[0].files[0]);
options = JSON.stringify(options);
formData.append('options', options); //include it in the form data and separate it on the server

$.ajax({
    url: "url",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (data) {

    },
    error: function (msg) {
        showMsg("error", msg.statusText + ". Press F12 for details");
        console.log(msg);
    }
});

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

The child component is not updating the v-model prop array of the parent component

In my current project, I have a main component called cms-custom-editor: <template> <div id="cms-custom-editor" class="cms-custom-editor"> <cms-editor-toolbar v-model:toggles="state.toggles"/> <d ...

Updating the content of a div using AJAX technology

Hi there, I have a functional PHP script that should be working fine. However, despite my best efforts to mimic similar jQuery Ajax functions from Stack Overflow, it just doesn't seem to work. I've included my HTML, PHP, and JS code below. Can so ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

XSL is the key component in creating a unique Custom Slider that remains stationary

I am currently working on a jQuery slider project and I am encountering an issue with getting the images to slide properly. The arrows seem to be functioning as expected, indicating that the necessary classes have been added, but the actual sliding action ...

An issue occurred when attempting to convert the XML response to Json format

Trying to convert XML response to JSON. I am making a request to an API endpoint that sends back XML data. After receiving the data, I successfully convert it to a json string. However, when attempting to deserialize the json string, I encounter an excepti ...

Exploring the usage of arrays within Angular 4 components. Identifying and addressing overlooked input

I'm struggling with array declaration and string interpolation in Angular 4 using TypeScript. When I define the following classes: export class MyArrayProperty { property1: string; property2: string; } export class MyComponent { @Input() object: ...

Issues with PHP JSON and AJAX functionality are arising specifically when attempting to run them

Having successfully developed a site on my local machine, I encountered an issue after uploading it to my remote host - the ajax/json calls are failing to run. I have thoroughly checked for any html being written before the redirects are executed and the ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

assign various JSON datasets to a spinner widget

I'm facing a unique situation where I'm struggling to figure out how to connect this JSON response to a spinner. I've tried implementing it in a certain way, but unfortunately, I haven't been successful in retrieving all the values. Any ...

Display content in a div after the page is fully loaded with either a placeholder or animated loading

Hello everyone, this is my first post on here. I am relatively new to PHP, so any help or advice would be greatly appreciated. ...

How to trigger a hover effect on a div and its child simultaneously using HTML and jQuery

Here's my concept: I want the text to be contained within div elements with an integrated image, rather than just having fading in and out pictures. Here's my attempt: #first{ position: absolute; } #second{ position: absolute; -we ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

Is it possible to incorporate a PHP line within a Handlebars context array?

I'm currently utilizing handlebars along with a handlebars register helper to iterate through an array that I've included in my context. The result is then displayed as an unordered list (ul). However, I'm facing an issue when attempting to ...

Ways to display a specific HTML element or tag depending on the given prop in VueJs

When working with Vue.js, it's important to remember that a <template> can only have one root element. But what should be done if you need to render different html elements based on a prop? For instance, let's say we have a <heading> ...

An efficient way to store a JavaScript-generated countdown timer in MySQL using PHP

Can anyone provide guidance on how to save a JavaScript-rendered countdown timer into a MySQL database using PHP? For example, I have a button that, when clicked, triggers the countdown timer to start. My issue lies in figuring out the best method to ensu ...

Using MediaQuery from react-responsive to selectively hide individual JSX attributes

I have a button element that includes both the Profile Picture and the Info, which consists of the first name and last name. My goal is to hide only the profile picture (profileImageProps={profileImageAndBasicInfoProps.profileImageProps}) when the screen ...

The assignment of type 'string' to type 'UploadFileStatus | undefined' is not permissible

import React, { useState } from 'react'; import { Upload } from 'antd'; import ImgCrop from 'antd-img-crop'; interface uploadProps{ fileList:string; } const ImageUploader:React.FC <uploadProps> ...

Fast JSON retrieval

I am attempting to implement an instant search feature using json. Despite my efforts, the code does not seem to be functioning properly. Can someone kindly review it and assist me in resolving the issue? Thank you in advance. http://jsfiddle.net/hMyr7/ ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

What are some techniques for ensuring a CSS div remains stable and intact when adjusting the browser size?

Is there a way to prevent the entire website from resizing when you minimize or maximize your browser? I want the website size to adjust in proportion to your resize without reorganizing everything. How can this be achieved while maintaining the site lengt ...