How can you ensure that axios is able to post form data by passing it through the submit listener?

Here is a form example:

<form class="comment-post" method="POST" action="/api/v1/comment/<%= post._id %>" enctype="multipart/form-data>
   <div class="comment-section">
         <textarea rows="4" name="comment"></textarea>
         <button type="submit" class="button">Submit</button>
  </div>
</form>

If there are multiple forms with the class 'comment-post', you can add an event listener for form submission to make an ajax request, like so:

const commentPostForms = document.querySelectorAll('.comment-post')

commentPostForms.forEach(form => {
    form.addEventListener('submit', function(e) {
        e.preventDefault()

        axios
            .post(this.action)
            .then(res=>{
                console.log(res)
            })
            .catch(console.error);

    })
})

The issue is that no form data is being sent along with the axios request. To fix this, you can do the following:

function(e) {
    e.preventDefault()
    const formData = new FormData(e.target)

     axios
        .post(e.target.action, formData)
         .then(res=>{
              console.log(res)
          })
         .catch(console.error);

 })

On the server side using Node.js and Express, you can log the received object from the form data:

router.post('/comment/:post_id/', comment );

const comment = (req, res) => {
    console.log(req.body)
    res.json(req.body);
}

However, if 'comment' is not appearing on the req.body in the console log, there might be an issue with how the form data is being passed.

Answer №1

To create the form data, utilize the event target. Update your code to:

const commentPostForms = document.querySelectorAll('.comment-post')

commentPostForms.forEach(form => {
    form.addEventListener('submit', (e) => {
        e.preventDefault()
        const formData = new FormData(e.target);

        axios
            .post(e.target.action, formData)
            .then(res=>{
                console.log(res)
            })
            .catch(console.error);

    })
})

Make sure in your HTML that you set the enctype attribute to form data like this:

<form class="comment-post" enctype="multipart/formdata" action="/api/v1/comment/<%= post._id %>">
   <div class="comment-section">
       <textarea rows="4" name="comment"></textarea>
       <button type="submit" class="button">Submit</button>
  </div>
</form>

If you want to verify the key/value pairs of your form data, you can do so after generating the form data:

for (let pair of formData.entries()) {
   console.log(pair[0]+ ', ' + pair[1]); 
}

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

Enhancing FireFox browsing experience with seamless server connectivity

In the process of developing a Firefox plugin that will interact with an http-server to both retrieve and send data, I am facing some challenges. The main goal of the plugin is to identify the current URL of the user and automatically pull related data suc ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Unable to remove the necessary row with Angular.js/JavaScript

I am facing an issue in deleting the correct row from an array using Angular.js. Below is the code snippet that I am working with: <tr ng-repeat="d in days"> <td>{{d.day_name}}</td> <td> <table ...

Retrieve a variable with jQuery and incorporate it into the view in Laravel 5.3

I am utilizing jquery to fetch data from a controller. The controller method returns a $user, yet I am unsure how to utilize it in the view. Below is the snippet of my code: <li> <a href="#suppression" data-toggle="modal" onclick="getForm(&a ...

How a Dynamic Icon Component in NextJS/React can disrupt Jest testing

Hello there! I'm a new member of this community, and usually I can find answers to my questions by searching. However, this time around, I need some help. My Current Setup I am using NextJS solely as a framework application without utilizing its API ...

Customize Highcharts axis properties after adding additional series to the plot

When working with highcharts, I utilize the xAxys and yAxis properties to format the inserted data. The code used is the same for both axes, so I'll provide an example for one of them: $('#containers').highcharts({ .... .... yAxis: { ...

How to replicate the content of a <template> tag using jQuery

Is there a way for me to clone the content of a tag using jQuery without losing the events associated with the child elements? ...

Navigating jQuery Tabs by Linking to a Specific Tab in a Separate File

I am currently using Bootstrap 3 to develop a basic website. On the about.html page, I have set up Tabs with various content. <ul class="nav nav-tabs" id="TabSomos"> <li class="active"><a href="#somos" data-toggle="tab">About Us</a> ...

Tips for changing the content of a td element to an input field and removing the displayed value

I am facing an issue with a dynamic table that displays names and input fields. When a name is displayed in a table row, the user has the option to delete that name. I am able to remove the value from a specific table row, but I am struggling to replace th ...

What is the process for importing a JavaScript file into a Vue component?

Having trouble importing JSON results into a Vue component? The results are as follows: [{"id":"d023c5e3-ca3c-4d97-933a-1112a8516eee", "score":9001, "updated":"2018-12-07T13:48:33.6366278", "player":Johanna, "category":Funny}, {"id":"398b65fb-e741-4801-b ...

Top storage solution for ExpressJS in the world of NodeJS

Embarking on the journey of creating my first substantial NodeJS application. My primary focus is achieving top-notch performance as the project involves a large AJAX (AngularJS) interface with numerous requests from multiple users. Currently in the proce ...

The Laravel controller is producing a JSON response that is coming back as undefined

Greetings! I am working with a JSON array and running the following code in my AJAX call: $('tbody').html(data.table_data); When I receive the response, it looks like this: [{"id":28,"fname":"tester","lname":"testlast","phone":"00000000","emai ...

What is the best way to save a reference using a POST API in NodeJs?

Currently utilizing the express.js framework for building a MERN stack application. This is my first endeavor into creating a full-stack JavaScript app, so a lot of the functions are new to me. I am in the process of sending a new post to a topic and updat ...

How can we display a modal and update data dynamically using setInterval in an Ajax function in CodeIgniter with PHP?

I'm having trouble setting up an alert for all users when the time runs out. I've implemented a condition where if the days, hours, and minutes all reach 0 (zero), then the Modal and setInterval should be triggered. However, my current code doe ...

Running a script within an Ajax-rendered form using remote functionality in a Ruby on Rails

After clicking the following button, my form is rendered: = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true The form is rendered using the script below ...

Utilizing Ajax with fullCalendar for consistently refreshing events with the refetchEvents

I have encountered an issue with FullCalendar and the refetchEvents function. I am using a python script to add a new event to a Google Calendar, which serves as the eventSource for my FullCalendar. However, after adding the event and attempting to reload ...

When integrating matter-js and applying a Body using fromVertices, the alignment of the resulting vertices may be inaccurate in relation to one another

Take a look at the shape I'm anticipating. The vertices along the edge outline the points. https://i.sstatic.net/YpQrR.png This is the json file (derived from the image above) that I'm importing and using to construct the Body. { "cann ...

Steps on how to set the values of a select option based on a JSON parsed array

After receiving an array from a JSON call, I am trying to populate a select element with the data. {1:Android, 2:IOS, 3:Business Management Systems, 4:Database, 5:Codes/Scripts, 6:Others} or 1: "Android" 2: "IOS" 3: "Business Management Systems" 4: "Da ...

Having trouble getting Bootstrap's Javascript to function properly in a Rails 6 webpacker configuration?

Recently initiated a brand new Rails 6.0.3 project and integrated jQuery and Bootstrap into it. Surprisingly, jQuery is functioning smoothly, and the Bootstrap CSS appears to be rendering correctly. However, every attempt to execute $.fn.tooltip.Construc ...

site.js problem

Recently, I decided to create my very own CS:GO gambling website. After successfully setting it up on my localhost using VPS, I moved on to getting a domain and finalizing everything. However, when attempting to run site.js, an error message popped up: [e ...