How to send a form data through a POST request in Vue.js

There is an endpoint available for submitting data using a POST request,

http://localhost:3000/entry

The required keys are fname, lname, age

By sending a POST request to the specified endpoint, a new entry will be created.

Currently, I am attempting to submit a form using VueJS. However, when trying to call the API within the form, the data is not getting submitted. I have verified the network calls and it shows that no data is being sent to the endpoint.

HTML Code:-

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.16/vue-resource.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">

<div id="vueApp">
  <div class="container">

    <div class="row">
      <div class="col-sm-12">
        <h3>
          Dashboard
        </h3>
      </div>
    </div> 

    <div class="row">
      <div class="col-sm-12">
        <div class="form-group">
          <label for="fname">First Name</label>
          <input type="text" class="form-control" value="" v-model="fname" />
        </div>
        <div class="form-group">
          <label for="lname">Last Name</label>
          <input type="text" class="form-control" value="" v-model="lname" />
        </div>
        <div class="form-group">
          <label for="age">Age</label>
          <input type="text" class="form-control" value="" v-model="age" />
        </div>
      </div>
      <div class="col-sm-12">
        <a href="#" class="btn btn-success" @click="submitEntry">Submit</a>
        <span v-if="ajaxRequest">Please Wait ...</span>
      </div>
    </div> 

    <div>&nbsp;</div>

    <div class="row" v-if="debug">
      <div class="col-sm-12">
        <pre>{{ $data | json }}</pre>
      </div>
    </div>

    <!-- Table Start -->

    <div class="row">
      <table style="width:100%">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
        <tr>
          <td>{{fname}}</td>
          <td>{{lname}}</td>
          <td>{{age}}</td>
        </tr>
      </table>
    </div>
    <!-- Table END -->

  </div>
</div>

Javascript Code (script.js) :-

Vue.http.options.emulateJSON = true;

new Vue({
    el: '#vueApp',
    data: {
        debug: true,
        fname: '',
        lname: '',
        age: '',
        ajaxRequest: false,
        postResults: []
    },
    methods: {
      submitEntry: function() {
        this.ajaxRequest = true;
        this.$http.post('http://localhost:3000/entry', {
              fname: this.fname,
              lname: this.lname,
              age: this.age
            }, function (data, status, request) {
                this.postResults = data;

                this.ajaxRequest = false;
            });
      }}
});

CSS Styling (style.css) :-

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;    
}

Answer №1

Feel free to give this a shot.

axios.post('http://example.com/submit',{ data: { first: this.first, last: this.last, years: this.years }})
.then(response => this.responseData = response.data)
.catch(error => {});

Prior to utilizing this code snippet, ensure you have connected with the Axios Content Delivery Network (CDN).

https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a2bbaaacb083f3edf2f1edf3">[email protected]</a>/dist/axios.min.js

Answer №2

Although this information may be a bit outdated, I recently encountered the same issue of no data being sent to the specified endpoint (and interestingly, this post shows up first on Google). The issue stems from vue-resource's $http.post() function defaulting to sending data as resource/json rather than as a form. To correctly submit a form, it is necessary to set emulateJSON to true in order to send the request body as application/x-www-form-urlencoded content type.

Additionally, the outcome is a Promise, indicating that then() must be employed to handle the response, as mentioned by @ribas.

Hence, the revised submitEntry() function in the above example should look like:

      submitEntry: function() {
        this.ajaxRequest = true;
        this.$http.post('http://localhost:3000/entry', {
            fname: this.fname,
            lname: this.lname,
            age: this.age
          }, {
            emulateJSON: true  // <-- Previously omitted
          }).then(function (data) {  // <-- Response handling 
            this.postResults = data;
            this.ajaxRequest = false;
          });
      }}

While opting for an entirely different library such as axios is completely acceptable and actually recommended by Evan You (Vue's creator), it does not resolve the underlying issue with using the vue-resource ajax library.

Answer №3

What about trying this approach?

this.$http({method: 'POST', url: URL, data: data})
.then(response => {
   this.postResults = data;
   this.ajaxRequest = false;
}).catch((err) => {
  console.log(err)
})

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

Looking to locate an array within a schema using its unique identifier

const FormFieldsSchema = new Schema({ formName: { type: String, required: true }, fields: [ { fieldLabel: { type: String, required: true }, inputData: [{ type: mongoose.Schema.ObjectId, re ...

Using bootstrap with a navbar in an asp.net mvc application proves to be challenging

There are only a few bootstraps that work with this site, such as the default and lumen bootstrap. You can find them on However, other bootstraps like materia and flatly seem to be causing display issues. Here's an example of how it looks: Edit: Bel ...

Error: Encountered an unforeseen symbol '<' during AJAX request

I'm in the process of creating a JavaScript array to help me determine the online status of various streams. However, whenever I attempt to alert the output, I keep encountering an unexpected token '<' error at line 1 of my document. It&a ...

Tips for removing JavaScript functions that were initialized after an ajax request

In my setup, there are two main pages: Page A and Page B. Page A consists of the following components: HTML for Page A JavaScript for Page A JavaScript for Page B Subsequently, I utilize an ajax call to inject Page B's HTML into Page A and trigger ...

Angular filter function encounters an issue if the value being filtered is null

Currently facing an issue while filtering an array. Whenever the filtered field is null, it triggers an error causing the rest of the code to fail. This is how my code looks like: this.order= result.headerText.find((item) => item.textType === 'Orde ...

Something is wrong with the conditional compilation in the JavaScript code

I encountered a "Conditional compilation is turned off" error in my JavaScript code. How can I resolve this issue? var <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="176264726559767a722a6765727a763976397679747f786557626739786 ...

Leveraging the execute script command in Selenium IDE to determine the time duration between two dates displayed on the webpage

For work automation, I've been utilizing SIDE to streamline certain tasks. One challenge I'm facing involves extracting dates from a page using the store command and then attempting to calculate a duration using the execute script command, which ...

Express.js applications automatically share the Mongoose connection

Currently, I am in the process of building a RESTful API using Express.js and Mongodb with the mongoose module for database access. I wanted to find the most efficient way to share the Mongo database connection throughout my entire Express application to a ...

Shipment calculation involves the consideration of factors such as the quantity,

Hello, my name is Mirella and I am from Italy. Please bear with me as I communicate through Google Translate. I am facing some issues with shipping costs while using Simplecart. My customers have varying shipping costs based on the items they purchase. T ...

The process of eliminating line breaks in javascript is not functioning as expected

I've been searching all over the place, experimenting with different methods, but I just can't seem to fix this issue.. var save_field = res[0]; var save_value = res[1]; save_value = save_value.replace(/\n/gm, '<br />'); con ...

The Protected Routes in React Router Dom persistently redirecting

I am currently implementing protected routes in my Redux and Pure React app using React Router Dom. The issue I am facing is that when I navigate to /profile/edit and then refresh the page, it automatically redirects me to /login and then to /profile. I ha ...

Arranging Elements in a Vertical Stack Using Bootstrap

I'm currently working with bootstrap to arrange a series of cards side by side, but I'm facing an issue where the cards end up stacking on top of each other instead of aligning horizontally. <div class="container"> <div class="row"& ...

Make sure that a specific div or image is loaded first

When loading the following code, my priority is for "div1" to load before anything else. <HTML> <body> <div id="div1">This div should be loaded first</div> <img src="/" title="Other large images"&g ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...

Asynchronous handling of Three.JS geometry operations

I've been developing a browser-based game that retrieves terrain data from a remote server. My current implementation involves creating a PlaneGeometry with 100x100 segments based on the received data. However, when the terrain is added to the game ...

Tips for adding content to several elements at once using jQuery

My HTML structure is as follows : <span class="section2 section4">hello</span> <span class="section1">World</span> <div class="tab" id="tab1"></div> <div class="tab" id="tab2"></div> <div class="tab" id= ...

Change the class name using jQuery when scrolling

Currently utilizing bootstrap as my primary css framework. My goal is to dynamically toggle a class on the navbar once the user scrolls past the prominent header image located at the top of the website. UPDATE: Admitting I made an error and had a momenta ...

What led to the decision for the two distinct chart elements to merge into a single container?

In the process of creating a dashboard using React.js and d3.js, I encountered an interesting issue that perplexed me for quite some time. Below is the Scatterplot.js code written in d3.js: import React, { Component } from "react" import * as d3 from "d3 ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Retrieving data from the database into a DIV using ajax

Here is the code snippet I am using to retrieve values from my database at regular intervals: <script type="text/javascript"> $(document).ready(function(){ var j = jQuery.noConflict(); j(document).ready(function() { j(".refreshMe ...