What is the best way to send Array Data using Vue's axios library when getting Data from an API?

I've encountered an issue where a form with dynamically generated inputs based on API results is causing trouble. I can successfully retrieve data using Axios, but when trying to submit the user-entered data array back to the API, it fails.

Here's the template structure:

<form @submit.prevent="getReference" class="form-material form-horizontal">
  <div class="row">
    <div class="col-md-6"
      v-for="(item, index) in items"
      :key="item.id">
      <div class="card bg-light-inverse ribbon-wrapper">
        <div class="card-block">
          <div class="ribbon ribbon-danger">{{index + 1}}</div>
          <div class="row ribbon-content">

            <input v-model="item.id" />
            <label class="col-md-12 text-themecolor">Enter Amount To Pay</label>
            <div class="card col-md-12 m-t-10">
              <input
                v-model.number="item.amount"
                type="number"
                class="form-control"
                placeholder
                max
                min
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <button
    class="btn btn-rounded btn-outline-danger waves-effect waves-dark"
  >Get Refrence</button>
</form>

And here's the corresponding JavaScript code:

export default {
  data() {
    return {
      items: {},
      item: []
    };
  },
  created() {
    let uri = `/Api/${this.$route.params.id}/items`;
    this.axios.get(uri).then(response => {
      this.items = response.data;
    });
  },
  methods: {
    getReference() {
      console.log(this.item);
      let uri = "/api/reference";
      this.axios.post(uri, this.item).then(response => {
        this.$router.push({ name: "fee" });
      });
    },
  }
};

Despite my efforts, attempting to submit the form results in nothing being sent and an uncaught exception: Object error in the console. I'm struggling to identify the problem. Any assistance would be greatly appreciated.

Answer №1

When working with the template section, you're looping through the items as item and using that same item for binding inputs. However, when sending data via axios, you're using this.item.

Since you are already binding input data to the items themselves due to the loop, consider sending items instead of item in the axios section.

  methods: {
    getReference() {
      console.log(this.item);
      let uri = "/api/reference";
      this.axios.post(uri, this.items).then(response => {
        this.$router.push({ name: "fee" });
      });
    },
  }

To avoid issues with binding values in the input section, it's recommended to remove item from the data section entirely.

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

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

clicking the table to export it to Excel

Currently, I am facing an issue while working on IE9. The code below is meant to download a HTML table as an excel spreadsheet: <a id="toExcel" onclick="window.open('data:application/vnd.ms-excel,' + document.getElementById('resultsTable ...

Implementing debounce for an onclick function in a TypeScript React application

Looking to incorporate the lodash debounce function into an onclick event to prevent multiple clicks on a button. My approach is as follows: function saveForm() { //do stuff here } <Button onClick={debounce(() => saveForm, 1500, { maxW ...

Having issues with my custom AngularJS directive functionality

app.directive("myData", function() { return { templateUrl: '/my-data.html' }; }); my-data.html file code <tr ng-repeat="employee in employees"> <td>{{employee.id}}</td> <td>{{employee.name}}</t ...

The AJAX call failed because the web service was not properly configured, resulting in a missing parameter value being

I'm encountering an issue with my ajax call that displays a specific message. [WebMethod(EnableSession = true)] public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets) { // conducting server-side processing return "a u ...

What is the reason behind asynchronous module resolution behavior caused by relative imports from a parent index file using '..'?

In my repository, the structure is as follows: src/ index.ts main.ts bar/ file.ts index.ts foo/ fooFile.ts The purpose of src/index is to serve as a top-level index file that exports all elements in my package. However, I h ...

Cross-site HTTP requests in Vue Resource

When I send a jQuery request to an external server, it follows Cross-site HTTP request rules by sending an OPTIONS request first to verify the endpoint's existence before executing the actual GET request. Everything works fine with jQuery, but I want ...

Why do the non-space characters in the string not convert to uppercase?

I'm looking to create a function that can convert characters in a string at even indices to uppercase, while ignoring spaces as even indices. For example: 'This is a test' should become 'ThIs Is A TeSt' My initial solution didn&a ...

Utilizing controller variables within ng-repeat in AngularJS

As I delve into learning AngularJS, I am attempting to utilize a variable from the controller in an ng-repeat without using scope. However, my code is not functioning as expected. Can someone help me identify and correct my mistake? Below is the snippet ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Simply input the data into the fields of the weekly tds

I am facing an issue with my code where, upon clicking the "apply to all" button, it automatically populates the columns for Monday through Friday only. However, I need Saturday and Sunday to remain empty without any data. $('#elemento').click ...

Tips for creating a custom Angular Material modal window that is fully responsive to its parent modal window

Hey there! I've put together a custom modal window in Angular Material by combining the custom modal window example with the Angular Material slider demo. Everything is working well except for the fact that the sliders inside the modal window are not ...

Create a smooth scrolling effect for a div with a fixed position

Having trouble scrolling a fixed position div on the page? Are you using this jquery script: $('html, body').animate({ scrollTop: $(".example").offset().top }, 750); I had to set the body overflow property to hidden for another issue. The ...

In react-native, both the parent and child components are rendered at the same time

One of my components, the parent one, goes through an array of chapters and for each item found, renders a child component called 'ExercisesList' and passes an array of exercises to it. class ExercisesScreen extends Component { displaySelected ...

What impact does the return value of jQuery's .not() have on the .hide() method?

I am encountering an issue with my HTML table and jQuery setup where rows are hidden when a user clicks on a specific topic, but I am uncertain about how it is functioning. Despite referencing the jQuery documentation, I am still confused about its behavio ...

Is it possible to reset npm sudo permissions back to their default settings?

After following the steps outlined in this article https://docs.npmjs.com/getting-started/fixing-npm-permissions (SECOND OPTION IN PAGE) to enable the installation of global modules without using sudo, I have successfully achieved the desired result. Howe ...

Using jQuery Plugin for Date Operations

I am in search of a jQuery tool that can assist me with date manipulations, such as: 1) Adding a specific number of days to a date and obtaining a new Date. 2) Determining the week of the year for a given date. 3) Calculating the number of days between two ...

Ways to incorporate physics into CSS animations

Creating a loading screen with CSS and aiming for realistic behavior can be a challenge. Utilizing the animation-timing-function: cubic-bezier(1, 0, 1, 1) property gives a decent result, but perfecting it requires understanding how the parameters in cubic- ...

Following my return from the Laravel password reminder, an error message stating 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' was displayed

This is the route for my home page, where a random member is selected: Route::get('/', function() { $member = User::orderBy(DB::raw('RAND()'))->first(); return View::make('landing', compact('member')); }) ...