Unable to make a post using vue.js

I am facing an issue while trying to submit form data using "vue-resource" in my code. The error message I receive mentions a problem with the use of this method alongside vue-cli and vuetify.

Error

[Vue warn]: Error in v-on handler: "TypeError: this.$http.post(...).error is not a function"

App.vue

<template>
  <v-app>
    <v-main>
      <v-container class="px-0">
        <v-form ref="form" @submit="addEvent">
            <p class="text-uppercase">Question?</p>
              <v-radio-group v-model="newEvent.select1" row>
                <v-radio label="aaa" value="aaa"></v-radio>
                <v-radio label="bbb" value="bbb"></v-radio>
              </v-radio-group>
            <input type="submit" depressed color="primary" value="OK!">
        </v-form>
      </v-container>
    </v-main>
  </v-app>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      users: [],
      newEvent: {
        select1: '',
      }
    }
  },
  methods: {
    addEvent: function (e) {
    e.preventDefault()
        if (this.isValid) {
          console.log("success")
          console.log("select1: " + this.newEvent.select1)

          this.$http.post('URL..', this.newEvent, function (data, status, request) {
            console.log("post success")

            console.log(status)
            }).error(function (data, status, request) {
              console.log("post failed")
            })
        }else{
          console.log("need edit")
        }
      },
  },
    computed: {
      isValid: function () {
        var valid = true
        for (var key in this.data) {
          if (!this.data[key]) {
            valid = false
          }
        }
        return valid
      }
    },
};
</script>
 

I have attempted adding "import VueResource from'vue-resource'" in main.js, but it did not resolve the issue. Can anyone help me find a solution?

Answer №1

Consider using either axios or fetch

// start by importing axios

import axios from 'axios'

// ... add your code here

axios.post(url, data).then(response => {}).catch(error => {})


// alternatively, you can use fetch

let response = await fetch(url, { method:'POST', headers: {'Content-Type': 'application/json;charset=utf-8'}, body: JSON.stringify(data) })

// extract the result
let json = await response.json()

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

"The Vue.js/JavaScript object updates, but the changes are not being displayed in the document object model (DOM

Currently, I am endeavoring to iterate through an array of objects and display them as list items. There is a click listener that introduces a custom property to the object, and a class binding depends on the value of that property. Would you mind reviewin ...

Keep track of open tabs and their content by utilizing sessions

I am working with Bootstrap Tabs where I have loaded content dynamically using jQuery's load() function. In addition, when a button is clicked, a new tab is generated automatically with a basic HTML form containing various input fields, which is then ...

Step-by-step guide on building an engaging Donut chart using jQuery

After spending several hours working on it, I'm struggling to draw my donut graph with JavaScript. Can anyone provide a solution? I am looking for a way to add 25% when one checkbox is selected and +25% when two checkboxes are selected. Thank you in a ...

Keep duplicating a single object until it fills up the entire screen

Is there a way to make an HTML/CSS element repeat until it covers the entire screen height, without repeating it indefinitely? #container{ height: 100vh; width: 100vw; } .dotts{ background-color: yellow; border-radius: 50%; height: 20px; width: 20p ...

Issue with returning value from promise object in Next.js

Hello! I am fairly new to JS and React, so I would appreciate your patience as I try to navigate through this. It has been quite a journey so far. In my component, I am fetching JSON data from a URL and attempting to extract a specific value from it to d ...

What is the proper way to invoke NuxtServerInit?

When attempting to make a REST API call using nuxtServerInit in the Vuex store, it doesn't trigger. However, if I make the API call in components or pages, it works fine. store/index.js import axios from 'axios' export const state = () =& ...

Why is it that when a boolean value is logged as a checkbox, it shows up as undefined?

In my code, I'm attempting to log the value of a variable named check, which corresponds to column 11 in a spreadsheet. This variable is meant to represent the state of a checkbox (true or false) based on whether it's been ticked or not. However, ...

JavaScript/jQuery countdown timer failing to initialize properly

Having some trouble with a countdown timer that I customized from the original version. The issue seems to be with startCountdown(startDate,deadlineDate,expiredText) as it's returning undefined. Any thoughts on what might be causing this? All relevan ...

What is the best way to conceal a global component like a navbar on specific routes?

Most of the pages on my vuejs SPA feature a top navbar component, but there are certain views like the login page where I do not want it to be displayed. My current solution involves importing the navbar and adding it to each view separately when needed. ...

Error: The method area is not supported for this.mesh.geometry

Recently, I've been experimenting with JavaScript, Three.js, and Leapmotion. To enhance my program, I decided to incorporate the leap widgets library which can be found here. However, after investing numerous hours into this project, I encountered a ...

Text area capacity

Is there a limit to the maximum capacity of a textarea for accepting text? The HTML page functions correctly when the text is limited to around 130-140 words. However, if the text exceeds this limit, it causes the page to hang without any response. The tex ...

Unable to transfer the component between components

This is the code I have: index.js: import React from "react"; import ReactDOM from "react-dom"; import {dest, People} from './components/people'; import json from './people.json'; function initFromJson() { let names = []; for(let ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Issue with Cloud Code function preventing data from being saved

After successfully testing this code in Angular and getting the correct responses in console.log, I decided to migrate it to cloud code. Since the function manipulates data in the user table, I had to use the master key and implement it in cloud code. Howe ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Can we modify a currently active document within MongoDB?

Is there a more efficient way to achieve the same functionality in JavaScript? I have to find a user, validate their password, and then update their document. Can I optimize this process by reusing the already retrieved document (stored in var doc) for up ...

Disabling the global ajax datatype causes issues with Rails remote links

I have successfully developed a rails application that submits a form remotely and then displays form validation errors if the validation process fails. The form itself is working perfectly. However, I've come across an issue where the way I've ...

Mastering the art of nesting loops and conditions in React: A comprehensive guide

I am fetching data in React using the following method: const data = [ { header: 'my header1', copy: [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Etiam et risus quam. Pr ...