Validation error occurred while attempting to send form data to the Contact Form 7 API through Next.js

Having trouble sending data to the Contact Form 7 API and encountering an error while submitting the form:

{into: "#", status: "validation_failed", message: "One or more fields have an error. Please check and try again.", posted_data_hash: "", invalid_fields:

The input fields on the form are correctly named, for example name="your-name"

Here's how I am attempting to send the form data:

  async function handleSubmit(e) {
    e.preventDefault();

    const formData = {};

    Array.from(e.currentTarget.elements).forEach((field) => {
      if (!field.name) return;
      formData[field.name] = field.value;
    });

    await fetch(
      "https://domain.tld/cms/wp-json/contact-form-7/v1/contact-forms/1234/feedback",
      {
        body: JSON.stringify(formData),
        headers: {
          "content-type": "multipart/form-data",
        },
        method: "POST",
      }
    )
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }

I've tested it in Postman and received a successful status message. Not sure what I'm missing here.

Below is the form structure:

<Form onSubmit={handleSubmit}>
    <Form.Group controlId="your-name">
      <Form.Control
        required
        type="text"
        placeholder="Your name"
        name="your-name"
      />
      <Form.Control.Feedback type="invalid">
        Please enter your name
      </Form.Control.Feedback>
    </Form.Group>
    <Form.Group controlId="your-email">
      <Form.Control
        required
        type="email"
        placeholder="Your email address"
        name="your-email"
      />
      <Form.Control.Feedback type="invalid">
        Please enter your email
      </Form.Control.Feedback>
    </Form.Group>
    <Form.Group controlId="your-message">
      <Form.Control
        as="textarea"
        cols={30}
        rows={6}
        placeholder="Write your message..."
        name="your-message"
      />
    </Form.Group>
    <Button
      type="submit"
      variant="primary"
      size="lg"
    >
      Send Message
      <span></span>
    </Button>
  </Form>

Answer №1

When working with a Content-Type that begins with multipart/*, it's essential to set the boundary in your code. If the boundary is missing, you may encounter issues.

To resolve this issue, utilize the FormData class by creating an instance like const formData = new FormData(). Then, add values using formData.append(key, value). By doing so, Axios can determine the data type being sent and automatically set the Content-Type along with the boundary.

The following code snippet should assist in resolving this problem (although it has not been tested):

async function handleSubmit(e) {
  e.preventDefault();

  const formData = new FormData();

  Array.from(e.currentTarget.elements).forEach((field) => {
    if (!field.name) return;
    formData.append(field.name, field.value);
  });

  await fetch(
    "https://domain.tld/cms/wp-json/contact-form-7/v1/contact-forms/1234/feedback",
    {
      body: formData,
      method: "POST",
    }
  )
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.error("Error:", error);
    });
}

Answer №2

I attempted this solution and found success, however, I encountered an issue where the data in the form fields remains even after successful submission. Additionally, I am facing challenges with file uploads as it is storing the wrong path. Image

The code snippet for reference -

export default function PageWithJSbasedForm() {
  // Function to handle form submission
  async function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData();

    Array.from(event.currentTarget.elements).forEach((field) => {
      if (!field.name) return;
      formData.append(field.name, field.value);
    });

    await fetch(
      "http:/www.example.com/wp-json/contact-form-7/v1/contact-forms/593/feedback",
      {
        body: formData,
        method: "POST",
      }
    )
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }
  return (
    // Event handler passed to handleSubmit() on form submit
    <form onSubmit={handleSubmit}>
      <label htmlFor="yourName">Your Name</label>
      <input type="text" id="yourName" name="yourName" required />

      <label htmlFor="yourAge">Your Age</label>
      <input type="text" id="yourAge" name="yourAge" required />

      <label htmlFor="yourFile">Upload File</label>
      <input type="file" id="yourFile" name="yourFile" required />

      <button type="submit">Submit</button>
    </form>
  );
}

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

Trigger the D3 component to re-render in React after a state change occurs in the parent component

My React project consists of two components written in TypeScript. The first component contains menus, and I am using conditional rendering to display different content based on user selection. <Menu.Item name="graph" active={activeItem ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Generate dynamic routes in Next.js only when needed

I'm currently working on a project using NextJS to create a frontend for a database that contains thousands of products, with the expectation of significant growth. The site/products/ route is functioning well, but I wanted to add a route to view indi ...

Tips for locking the button in the navigation bar while scrolling

I noticed that when I have 6 fields in my navbar, with 5 of them being links and one as a dropdown, the scrolling of the page causes all fields to remain fixed except for the dropdown field.Check out this image description for reference https://i.stack.im ...

Can you create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

Bootstrap4 does not support the <button> element

How can I achieve a 'collapse icon' floated to the left followed by Copyright © using Bootstrap 4? I've looked at similar questions on this topic, but none seem to provide a direct answer. Other questions contain different code with ob ...

Testing event emitters in node.js: a step-by-step guide

Imagine the scenario where I need to create a basic task. However, I also need to develop a test that validates the following criteria: The task should emit an object. The emitted object must have a property named "name". I am utilizing mocha and chai e ...

Learn the process of transforming a filter into a directive in AngularJS

Here is a question I asked previously, where I was looking to remove negative numbers from an input field: <input type = "text" ng-model="number"></input> In that previous question, Paritosh provided me with a helpful solution, but now I am i ...

What is the typical number of open CLI terminals for a regular workflow?

After experimenting with Gulp, Bower, ExpressJS, and Jade, I have settled on a workflow that I am eager to switch to. The only issue I am facing is the need to have two terminals open simultaneously in order to use this workflow efficiently. One terminal ...

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...

"Learn an effective method for presenting JSON variable data in a Bootstrap modal with a clean design using three distinct columns

I have successfully loaded JSON data into my HTML page using JQuery. By clicking a button, I can trigger a bootstrap modal that displays the content of the JSON variable. However, there is an issue with how the JSON data is displayed. I need the data to b ...

Executing JavaScript code within a class object using ASP-VB

I'm looking to create a function that will show a Javascript-based notification. I already have the code for the notification, but I'm trying to encapsulate it in a class library as a function. However, I am unsure about what to return from the f ...

AngularJS encountering unresponsive resources

When setting up my Angular App, I include various resources like this: angular.module('myApp', ['infinite-scroll', 'chieffancypants.loadingBar', 'ngResource']) Next, in the html file: <script type="text/javascr ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

Can you please share your methods for fetching and caching paginated collections, particularly within the context of Angular or Restangular?

In an app that retrieves data from a REST api with paginated collections of potentially infinite size, how can we effectively handle fetching, caching, and invalidating this data? Imagine the API endpoint is: GET /users?page=1&per_page=50 The respon ...

Integrating Django with ReactJS resulted in the following error: "Unable to fetch resource: the server returned a 404 (Not Found) status code."

I'm currently immersed in an e-commerce venture utilizing Django at the backend and ReactJS on the frontend. However, I've hit a roadblock while attempting to retrieve data from the ReactJS component to the Django backend. The dreaded error messa ...

Is it possible to configure Lambda NodeJS 12.x flags (like --experimental-modules) when using AWS SAM local start-api?

When setting up my nodejs server, I chose to use ES6 module syntax: package.json "type": "module" So far, running my server locally as a nodejs process has been successful. For example: "scripts": { "dev": "npm outdated ; nodemon --experimental-modul ...