2

I'm trying to create a JSON object from form data on submit.

I've managed to get it working with a variable. Is there a better way to create a JSON object?

Form

<form @submit.prevent="submit">
   <div class="form-group">
      <label class="inputa-label" for="exampleInputEmail1"
         >Email address</label
         >
      <input
         type="email"
         class="form-control inputa"
         id="exampleInputEmail1"
         placeholder="Enter email"
         required
         v-model="email"
         />
   </div>
   <div class="form-group">
      <label class="inputa-label" for="exampleInputPassword1"
         >Phone number</label
         >
      <input
         type="number"
         class="form-control inputa"
         id="exampleInputPassword1"
         placeholder="Phone"
         v-model="phone"
         />
   </div>
   <div class="form-group">
      <label class="inputa-label" for="exampleInputPassword1"
         >Information</label
         >
      <textarea
         class="form-control inputa"
         aria-label="With textarea"
         v-model="information"
         ></textarea>
   </div>
   <button
      type="submit"
      style="font-weight:600; padding: .8125rem 1.25rem"
      class="btn btn-primary"
      >
   Submit
   </button>
</form>

Method:

  data() {
    return {
      email:"",
      phone:"",
      information:"",
    };
  },
  methods: {
    submit() {

      var data = '{ "Email":"' + this.email + '" , "Phone":"' + this.phone + '", "Information":"' + this.information + '" }';
      
    },
  },

I've got it working with a variable, but I want to know if there is a better way to do this.

3
  • 1
    Just a reminder that the default submit functionality takes care of sending the form data for you and you don't need to generate a JSON payload yourself. However, if you still wish to send some custom payload, if you're using Axios, you may just supply a javascript object in an axios.post request! Commented Nov 25, 2020 at 8:01
  • I am posting the variable "data" with axios. I just wanted to know if there was a more proficient way to do this rather than how I have with my variable. Thanks @Ayudh Commented Nov 25, 2020 at 8:11
  • you can make it from json object, then use JSON.stringify Commented Nov 25, 2020 at 9:11

1 Answer 1

7

Answering the question, I think what you're looking for is JSON.stringify():

const data = JSON.stringify({
  Email: this.email,
  Phone: this.phone,
  Information: this.information
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.