Tips for updating data in vue.js

I am currently facing a challenge where I need to use vue.js to edit and update values.

While I have successfully implemented the edit functionality to retrieve the values, I am encountering difficulties with updating them.

To trigger the update action, you can click on the following button:

<span><button type="submit" @click="updateItems" name="add" class="btn btn-default hidden-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Save"><i class="fa fa-floppy-o"></i><span class="hidden-sm hidden-xs"> Save</span></button></span>

Here is the script for the Edit functionality:

<script>
import config from '../../../config';
export default {
  data(){
    return{
      items: [],
      itemsData:{
        room_id : '',
        start_date : '',
        end_date : '',
        package_id : '',
        price : '',
        child_price : '',
        discount : '',
        discount_type : '',
        people : '',
        price_sup : '',
        fixed_sup : '',
        tax_id : '',
        taxes : ''
      },

      errors: {

      }
    }
  },

  created: function() {
    this.fetchRates(this.$route.params.id);
  },

  methods:{
    fetchRates(id){
      axios.get(config.apiDomain+'/Rates/'+id+'/edit').then((response)=>this.itemsData = response.data);
    },

    updateItems(e){
      axios.put(config.apiDomain+'/Rates/'+this.$route.params.id, this.itemsData).then(response=>{
        // this.this.itemsData = "";
        this.$router.push('/admin/rates');
      }).catch(error=>{
        this.errors = error.response.data;
      });
    }
  },


  mounted() {
    axios.get(config.apiDomain+'/Rates').then((response)=>this.items = response.data);
  }
}
</script>

Below is the Update Controller code snippet in PHP:

 <?php

namespace App\Http\Controllers;

use App\Rates;
use Illuminate\Http\Request;

class RatesController extends Controller
{
  // Methods for handling index, create, store, etc.

}

The issue being faced includes:

XMLHttpRequest cannot load http://localhost/booking/booking-api/public/Rates/1. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

In addition, there is an error stating:

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
    at eval (RatesEdit.vue?5784:221)

If anyone has suggestions for resolving these issues and ensuring that the edited values can be successfully updated upon clicking the save button, please provide your insights. Thank you!

Answer №1

To resolve the issue, modify the put function of your REST API to a get function (and ensure that you update your route.php file, especially if you are using Laravel).

I faced a similar problem in the past and my suggestion is to stick with utilizing only the GET and POST methods for your REST API.

Hopefully, this advice proves useful for you.

UPDATE:

Replace the following code block:

Route::resource('Rates', 'RatesController');

With this updated version:

Route::get('Rates/{id}/edit', 'RatesController@update');

The reason behind this change is that when you call a GET method on the server, it cannot properly map to the update function on the server side.

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

Utilize Botium Scripting Memory Variables to Enhance Asserter Functionality

Consider the following test.convo.text example: Test asserter #me Show my json #bot $json MY-CUSTOM-ASSERTER $json The asserter recognizes '$json' string as arguments. I need the JSON response from the bot to be passed as arguments. Is the ...

Using an image for the axis in Wijmo BarGraph

I am currently working with Wijmo barcharts and attempting to create a graph that uses images instead of labels on the x-axis. The code I have at the moment displays the image source as a string rather than displaying the actual image. Does anyone know ho ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Extracting a single string from a JSON object: A step-by-step guide

Currently, I am working on retrieving a JSON document from my MongoDB. Once fetched, my goal is to extract only the "email" field so that I can utilize it for sending emails to users. setInterval(()=>{ return User.find({email: &apos ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

What are some methods for utilizing the data received through this.props.history?

Whenever I need to navigate from one route to another using this.props.history.push("/"), I also want to pass along some extra data. For example: this.props.history.push('/postDetail', {data: item}). However, I am uncertain about where to define ...

Ways to assign values to HTML table cells

I am facing an issue with two table cells where one span is located outside the td tag and the other is wrapped around td. <tr height="30"> <span data-name="toDD1" class="sstNumber"> </span> <td>Y</td> <span d ...

Unable to fetch Title from Strapi

I have a collection type named posts with the following values: https://i.sstatic.net/49OeV.png To access the API, I have a file in my lib folder that contains the following code: export async function getPosts() { var api_base_url = process.env.API_BASE ...

JavaScript Closures can utilize a shared global setting object or be passed as an argument to individual functions

Looking for advice on the use of a global "settings object" in relation to JavaScript closures. Should I access it from within functions in the global scope or pass the object every time a function requires access? To provide context, here's a mockup ...

Looking to implement a star rating feature in Vue.js 2?

My perspective is as follows : <div class="col-md-8"> ... <star-rating :value="3"></star-rating> ... </div> This is how my star-rating component looks like : <template> <span class="rating"> &l ...

Verify and send form without reloading the page

I am currently facing an issue with jQuery validation and ajax form processing. My goal is to prevent a page refresh by using ajax, but I am struggling to determine the appropriate placement for the ajax code within the validation function in order to ensu ...

Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...

The $scope variable is missing from the DOM

I've been trying to implement ng-repeat with AngularJS, but I'm having trouble getting the scope result in my DOM. Is there something wrong that anyone can spot? I've spent hours troubleshooting this and no matter what I do, "players" always ...

Stretching a row in Wordpress Visual Composer and setting the direction to Right-to-Left

Whenever I attempt to expand a row using the row settings in Visual Composer, the row stretches but the alignment of the row becomes completely off. This issue only occurs when the body direction is set to direction:rtl in the CSS. You can view the websit ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

Even though I am attempting to submit a form without refreshing the page using Ajax, it is still causing

I've searched high and low, read through numerous examples on various forums, and attempted to find the solution to my query but unfortunately, it still eludes me. Here's the particular scenario I'm facing: Main.php The main.php page featu ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Load website once AJAX has finished

Currently, I am using an ajax call to retrieve the color scheme of my website from the database due to having multiple clients with different schemes. My goal is to ensure that the page only loads after the ajax call has completed. Despite an expected dela ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...