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

Delay Export of React Component Until After Request in Shopify App Development

Being a newbie in Shopify App Development, React, and Next.js, I may have a silly question. Currently, I am making a request to a website and using the response in the React component that I want to export/render. To avoid it being undefined, I need to wai ...

Guide on crafting a side navigation menu that mimics the sleek functionality of mobile applications

Looking to develop a web app and mobile app hybrid, I started using bootstrap, jQuery, and Vuejs. Now, I aim to create a navigation menu that slides in from the left or right, similar to what we see in many mobile applications. To achieve this, I explored ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

What is the process for uploading an image encoded in base64 through .ajax?

I am currently working with JavaScript code that successfully uploads an image to a server using an AJAX call. Here is the ajax call snippet that is functioning properly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

Tips on leaving comments inside a render <div>

Hey there! I'm facing an unusual issue in my React+Webpack project. Even though I marked a line as a comment using //, it still gets rendered in the HTML output. Strangely, I have never encountered this problem before and can't figure out what tr ...

How can I ensure that my function only returns a value once the ajax call has finished?

Using mootools, I have a function that triggers an ajax script to retrieve a value. However, the function seems to return before the AJAX call is completed! What could be causing this issue... function getCredits() { var loadGlobalTab = new Request.J ...

How to properly size a child div inside a parent container

I'm having trouble with sizing a child div inside a parent div. The problem is that the child div's size changes according to the number of elements it contains, but I want all the child divs to be the same size regardless. This issue arises with ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

Shifting a division using insertAfter

Hey there! I'm having a bit of trouble using the insertAfter function. In each product in my store, I need to position an "add to cart" button after the price. This is the code I tried: <Script type="text/javascript" > jQuery(document).read ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

Unable to transmit the element identifier information through ajax

Whenever I attempt to pass id data through ajax, I encounter an undefined variable error. The ajax function works smoothly with form data, but the issue arises when trying to extract the id value. Below is the PHP/HTML code snippet: <ul class="sub-men ...

Finding the inverse value from the Lodash get() function

My current approach involves utilizing the lodash get() method to retrieve values from an object. However, there are instances where I need to obtain negated values. Unfortunately, simply applying a negate symbol or negate method after retrieving the valu ...

Removing an active image from a bootstrap carousel: A step-by-step guide

Within my bootstrap carousel, I have added two buttons - one for uploading an image and the other for deleting the currently displayed image. However, I am unsure how to delete the active element. Can someone provide assistance with the code for this but ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Enable hyperlink to open in a new browser tab after user clicks on button embedded inside an iFrame

<head> </head> <div> <iframe src="https://....."></iframe> </div> I'm looking for a way to open the link in a new tab when clicking on this button. Currently, the page loads within the iFrame when clicked. I&a ...

Reduce the length of the text and display it upon hovering with the mouse

I am trying to figure out how to truncate text and have it expand on mouseover in a paragraph element. I attempted to truncate the content using a specific code, but I encountered an issue. While my current code expands the content when clicking on the el ...

Enhancing PHP function speed through pre-compilation with Ajax

I am curious about compiling server side functions in PHP with Ajax, specifically when multiple asynchronous calls are made to the same server side script. Let's consider a PHP script called "msg.php": <?php function msg(){ $list1 = "hello world ...

Ways to implement a filter pipe on a property within an array of objects with an unspecified value

Currently, I'm tackling a project in Angular 8 and my data consists of an array of objects with various values: let studentArray = [ { Name: 'Anu', Mark: 50, IsPassed: true }, { Name: 'Raj', Mark: 20, IsPassed: false }, { Na ...