Question about sending multiple Axios POST requests with parameters

I'm new to Stack Overflow and seeking help with a specific issue on my Rails backend and Vue.js frontend website.

The challenge I'm facing involves making two POST requests simultaneously when the submit button is clicked. My "Trips" controller and "User_Trips" controller are crucial for creating and linking trips in my database. For a newly created trip to display properly, a corresponding user_trip must also be generated.

Although my trip post works seamlessly, the user_trip post encounters obstacles. I believe the issue lies in passing the recently created trip's id as a parameter needed for creating a user_trip. Here's an excerpt of the code snippet from Vue.js that I'm grappling with:

<script>
import axios from "axios";
export default {
  data: function() {
    return {
      trips: [],
      errors: [],
      name: "",
      country: "",
      state: "",
      city: "",
      postal_code: "",
      start_date: "",
      end_date: "",
      image: "", 
      trip: this.trip
    };
  },
  mounted: function() {
    // axios.get("http://localhost:3000/api/trips").then(
    //   function(response) {
    //     console.log(response);
    //     this.trips = response.data.trips;
    //   }.bind(this)
    // );
  },
  methods: {
    submit: function() {
      var params = {
        name: this.name,
        country: this.country,
        state: this.state,
        city: this.city,
        postal_code: this.postal_code,
        start_date: this.start_date,
        end_date: this.end_date,
        image: this.image
      };
      axios
        .post("http://localhost:3000/api/trips", params)
        .then(response => {
          axios.get("http://localhost:3000/api/trips").then(
            function(response) {
              console.log(response);
              this.trips = response.data.trips;
            }.bind(this)
          );
        })
        .catch(error => {
          this.errors = error.response.data.errors;
        });
      var paramsTwo = {
        trip_id: this.trip.id
      };
      axios
        .post("http://localhost:3000/api/usertrips", paramsTwo)
        .then(response => {
          this.$router.go("/home");
        })
        .catch(error => {
          this.errors = error.response.data.errors;
        });
    }
  }
};
</script>

The error message displayed in the console log is: Uncaught TypeError: Cannot read property 'id' of undefined. This leads me to suspect that I might not be selecting the correct trip from the array. However, upon reviewing the GET request in the log, the newly created trip doesn't appear - only in the database. Any useful suggestions would be greatly appreciated! - Thanks

Answer №1

Finally cracked the code! Much appreciation to all those who provided helpful comments and solutions.

<script>
import axios from "axios";
export default {
  data: function() {
    return {
      journeys: [],
      mistakes: [],
      name: "",
      country: "",
      state: "",
      city: "",
      postal_code: "",
      start_date: "",
      end_date: "",
      image: "", 
    };
  },
  mounted: function() {
  },
  methods: {
    completeForm: function() {
      var details = {
        name: this.name,
        country: this.country,
        state: this.state,
        city: this.city,
        postal_code: this.postal_code,
        start_date: this.start_date,
        end_date: this.end_date,
        image: this.image
      };
      axios
        .post("http://localhost:3000/api/journeys", details)
        .then(response => {
          console.log(response);
          this.journey = response.data;
          var newDetails = {
            journey_id: this.journey.id
          };
          axios
            .post("http://localhost:3000/api/userjourneys", newDetails)
            .then(response => {
              this.$router.go("/home");
            })
            .catch(error => {
              this.mistakes = error.response.data.errors;
            });
        }
        );
    }
  }
};
</script>

Answer №2

Your code is encountering an error at the paramsTwo line, causing your second submission to fail. Ensure that the object retrieved from your API includes an id property. Certain databases may return a _id property instead of id.

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

What is the best way to showcase the following values using Vue.js?

{"status":true,"data":[{"ref_id":"22","agent_id":"68","p_id":"84","description":"i am interested"},{"ref_id":"24","agent_id":"68","p_id":"84","description":"For more information about Bootstrap and Bootstrap Glyphicons, visit our Bootstrap Tutorial.For mor ...

Can you embed a VueJs Component using jquery?

I have a complex application where I previously utilized jQuery to dynamically change views: $(function(){ $(".changeview").bind("click",function(){ $.post(linkAction,phpData,function(data){ $('#loa ...

Utilize the power of passing multiple parameters in Vue.js methods while working on a Razor page

I am working on an asp.net core7 program that incorporates vue.js. My query pertains to passing parameters to the methods in vue.js. <i v-on:click="DeleteSale('@item.ID','@item.Image')" class="far fa-trash-alt cursor ...

Verify whether a pop-up window has been opened

Situation: Greetings, I provide a sensitive service to my clients. However, some of them are generating advertisement popups (using JavaScript) on their websites where my service is integrated, causing issues for us. My service involves a .js file hosted ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Challenges arise when transferring data retrieved from a table into a bootstrap modal window

I have been attempting to transfer values from a table into a modal. Initially, I successfully displayed the <td> values in an alert when a button was clicked on a specific row. Now, I am aiming to take it a step further by having these <td> va ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Is it possible to make changes to a box within a current PDF document using HummuJS?

I'm looking to update some existing PDF files with new data. According to the HummusJS documentation, I should be able to modify the box using parsing and modification techniques. However, I haven't been able to find the correct method to do so. ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...

Combining the power of Kendo UI with the flexibility of Vue

Hey there everyone, I'm currently utilizing the Vue.js CLI for my project. Recently, I came across a helpful tutorial on incorporating a Jquery plugin into a webpack project at this link: . To achieve this, I installed the expose loader and added th ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

Manipulating Images with jQuery: Adding and Removing Images Without Affecting Text

Below is the code I'm working with: <input type = checkbox id = "purple" name = "box" > Purple </input> <div id = birdcage></div> This is the JavaScript section: $("#purple").click(function(){ if ($("#purple").is(":chec ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

Utilize a Vue2 component that has been defined in the same file within another

I'm attempting to establish a reference from one locally defined vue2 Component to another in the following manner: new Vue({ el: '#app', components: { 'foo': {template: '<p>Foo</p>'}, 'bar&ap ...

Is it possible for an object hidden in the DOM using jQuery to magically reappear when you click the back button or use the bfc

Is there a way to prevent a box from reappearing when using the back button on a webpage? On my website, there is a box that shows up on the first visit. However, when navigating using the back buttons on the site or the browser back button, the box appea ...

Creating a global variable for both development and production APIs in Vue 3 is a key aspect in ensuring consistency

Creating a global variable that works for both production and development environments has been challenging. Despite efforts, the variable value remains undefined. I have set up .env and .env.prod files in the project's main directory. VUE_APP_ROOT_ ...

As the page is resized or zoomed in and out, the div elements start shifting in different directions

When I apply position:absolute to prevent the elements from moving when zooming in and out of the page, they all end up congregating in one place. Can anyone help me with this issue? None of the solutions I've found have worked so far. I'm develo ...

What is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance. Currently, only the 'All' option is working for applying any filtering logic. Here is how my HTML looks like with the filt ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

Having difficulty receiving a response from an AJAX call within the success function

After browsing through this stack link Ajax response not calling success:function() when using jQuery 1.8.3, I'm puzzled as to why the success function is not invoked when I uncomment the dataType line. It seems that setting dataType = JSON prevents t ...