Error message encountered while trying to instantiate 'FormData'

My contact form was working perfectly fine until recently when it suddenly stopped allowing me to send messages. I keep encountering this error message every time I try to submit the form:

Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'. at submitForm (ajax.js:77) at HTMLFormElement. (ajax.js:72) at HTMLFormElement.dispatch (jquery-3.3.1.js:5183) at HTMLFormElement.elemData.handle (jquery-3.3.1.js:4991)

$(document).ready(function() {
$("#subscribeForm").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        formError();
        submitMSG(false, "Are you sure you filled form inputs correctly?");
    } else {
        event.preventDefault();
        submitForm();
    }
});
function submitForm(){
            var subscribe_email =$("input[name=subscribe_email]").val();
            var formData = new FormData($(this)[0]);
            formData.append('subscribe_email', subscribe_email );
            $.ajax({
                 url: "include/ajax/subscribe.php",
                 type: "POST",
                 contentType: false,
                 processData: false,
                 data: formData,
                 cache: false,
                 success : function(text){
             if (text == "success"){
                 formSuccess();
             } else {
                 formError();
                 submitMSG(false,text);
             }
         }
     });
 }
function formSuccess(){
    $("#subscribeForm")[0].reset();
    submitMSG("valid", "Your message was successfully sent");
}
function formError(){
  submitMSG("invalid", "Something went wrong. Please, try again or contact with our support team.");
}
function submitMSG(valid, msg){
    if(valid){
        var msgClasses = "cf-alert alert success";
    } else {
        var msgClasses = "cf-alert alert warning";
    }
    $("#success_submit").removeClass().addClass(msgClasses).text(msg);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Can anyone help me figure out why my contact form suddenly started encountering this error? Any insights would be greatly appreciated. Thank you!

Answer №1

The error message is quite clear.

Uncaught TypeError: Failed to create 'FormData': the first parameter is not an 'HTMLFormElement'. at submitForm (ajax.js:77) at HTMLFormElement. (ajax.js:72) at HTMLFormElement.dispatch (jquery-3.3.1.js:5183) at HTMLFormElement.elemData.handle (jquery-3.3.1.js:4991)

var formData = new FormData($(this)[0]); // $(this)[0] is not a form element
In your code, $(this)[0] is linked to the global object (window in a browser)

You can pass a reference to your form like this:

$("#subscribeForm").on("submit", function (event) {
    event.preventDefault();
    submitForm(this);
});

function submitForm(myForm){
    const formData = new FormData(myForm);
    // or like this
    // const myForm = document.getElementById("subscribeForm");
    // const formData = new FormData(myForm);

}

In your situation, you can use the FormData constructor without any parameters since you are using formData.append()

const formData = new FormData();
formData.append("some_key", "some_value");

You can find more information about formData here

Answer №2

The issue lies within this particular line:

//var formData = new FormData($(this)[0]);

Fortunately, the solution is quite straightforward:

var formData = new FormData();

Following this, you can append whatever content you desire.

Answer №3

It appears that there is a duplicate element using the same id as the form #subscribeForm

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

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

The toggle button requires two clicks to activate

I created a toggle button to display some navigation links on mobile screens, but it requires two clicks upon initial page load. After the first click, however, it functions correctly. How can I ensure that it operates properly from the start? Below is t ...

What is the best way to execute NPM commands within the terminal of Visual Studio Code?

I recently installed npm in VSCode from extensions, but I am having trouble activating it. When I try to run the command 'npm init' in the terminal, I receive the following error message: "The term 'npm' is not recognized as the name of ...

Is the JavaScript Base64 image data damaged or compromised?

My current task involves selecting an image through an HTML Input and then retrieving the image using Javascript to obtain its Base64/Image Data string. However, the code I have implemented is only returning a partially corrupt or invalid representation o ...

Enhance the efficiency of a LINQ Query for AutoComplete functionality

Seeking ways to optimize the performance of my AutoComplete feature due to large search operations. Any suggestions or ideas would be greatly appreciated. Here's how it currently functions: 1) Upon application launch, all database entries are stored ...

GraphQL Error (Status Code: 429) - Next.js Development issue

If you're facing a GraphQL Error (Code: 429) while working on a nextjs project, here's a handy solution. Here's what happened: I created a headless CMS using Hygraph and NextJS 13 for a blog project. I also utilized the npm package graphql ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

Exploring the implementation of --history-api-fallback in webpack

let path = require('path') module.exports = { entry:path.resolve('public/src/index.js'), output: { path:__dirname + "/public", filename: "bundle.js" }, module: { loaders: [{ exclude: / ...

Modify a quartet of divs simultaneously

I am currently working on a project that involves 4 input fields, each accompanied by a dropdown element for selecting currency. My goal is to create a JavaScript function that will update all input fields when one of them is changed. For instance, if I s ...

How to Make Buttons Vanish and Reappear

Check out this fiddle for a picture button 'scroller' that I created. It may not be perfect, but my main focus is on making the arrow buttons fade in and out when reaching the end of the picture order. I am considering using a JavaScript functio ...

Displaying Data in a Pop-up Modal Using Codeigniter

I am currently facing an issue with my Modal Window. Although the javascript is working fine, I am unable to display any customer information in the Modal Window when clicking on the info button. How can I rectify this and successfully show customer inform ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

The functionality of `wp_ajax data_fetch` fails to operate properly in the presence of a Custom Post Type (CPT

When I include the custom post types ('applicazione' and 'miscele') in the array for 'post' and 'page', they are not being searched. However, when I only include the CPTs, it works properly. Can you please help me id ...