Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit a form using POST request in VueJS

I have an endpoint to submit data using POST request,

http://localhost:3000/entry

Keys are fname, lname, age

I can make a POST request into the given end point and it will create an entry.

I am trying to submit a form using VueJS. But, when I am calling the API within the form, it is not submitting the data. I have checked the network calls and it is not sending any data to the end point.

HTML :-

<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>

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;
            });
      }}
});

style.css :-

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;    
}
like image 933
Dinesh Ahuja Avatar asked Jul 19 '18 11:07

Dinesh Ahuja


People also ask

How do I submit form data to Vue?

We are getting name-value using a v-model directive. To upload the file and name value via form data, we declared both the values inside the data property: We need to declare the two event handler the onFileUpload() and onSubmit() inside the methods life cycle hook in the Vue component.

What is $data in Vue?

Data is the private memory of each component where you can store any variables you need. Props are how you pass this data from a parent component down to a child component. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.

Does Axios work with Vue?

Axios is a popular JavaScript library used to make HTTP requests. It is a promise-based HTTP client used in JavaScript or with other Javascript libraries like Vue. js or React.


2 Answers

You can try this one.

axios.post('http://localhost:3000/entry',{ params: { fname: this.fname, lname: this.lname, age: this.age }})
.then(response => this.responseData = response.data)
.catch(error => {});

Before using you need to link with Axios CDN

https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js

like image 171
Ziaur Rahman Avatar answered Oct 13 '22 00:10

Ziaur Rahman


Even though this is a bit old, I just ran into this same issue where no data was sent to the endpoint (and this question comes up first in Google). The problem is that vue-resource's $http.post() defaults to posting data as resource/json and not a form. To post a form, set emulateJSON to true which will send the "request body as application/x-www-form-urlencoded content type".

As an aside, the result is a Promise, which means then() should be used to handle the response (as @ribas correctly mentioned).

So the submitEntry() in the example above should be:

      submitEntry: function() {
        this.ajaxRequest = true;
        this.$http.post('http://localhost:3000/entry', {
            fname: this.fname,
            lname: this.lname,
            age: this.age
          }, {
            emulateJSON: true  // <-- This was missing
          }).then(function (data) {  // <-- Handle results like this
            this.postResults = data;
            this.ajaxRequest = false;
          });
      }}

Using a completely different library (axios) is fine and actually recommended by Evan You (creator of Vue), but it doesn't address the actual problem using the vue-resource ajax library.

like image 45
James Avatar answered Oct 13 '22 00:10

James