Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hardcode them, but I don't know how to pass the id into the async mounted axios function "api/sd/model/get", id)

Here is my template:

   
  <main class="home-page">
   
       <select v-model="selectedMark">
        <option v-for="model in items" :key="model.id">{{ model.name.value  }}</option>
      </select><br><br>

        <select v-model="selectedModel">
        <option v-for="make in info" :key="make.id" >{{ make.name.value }}</option>
      </select><br><br>

      
        <button type="submit" class="conectButton">Połącz</button>
      <div class="titleCarMain"><p class="titleCar">{{selectedMark}}</p><p class="titleComponent">{{selectedModel}}</p></div>
    
     
  
     </main>

This is the script:

import axios from 'axios';

export default {
  name: "App",
  data() {
      return { 
      
      info: null,
      items: [],
      selectedMark: null,
      selectedModel: null,

      };
  },
  
  async mounted() {
   axios
     .get("http://local/api/sd/make/get")
     .then(response => { this.items = response.data.data.items });
    

    const id = { id: this.selectedMark }  //doesn't work
     
    await axios
     .post("http://local/api/sd/model/get", id) //doesn't work 
     .then(response => { this.info = response.data.data.items });

   },
   
  
};

Can anyone help this newbie out? It would be amazing if you could also explain why your solution works for better understanding. Thanks in advance!

Answer №1

The current issue is that the component isn't functioning correctly because when it is mounted, selectedMark is initially set to null. In order to successfully fetch data from the "http://local/api/sd/model/ge" endpoint within the mounted hook, you need to somehow define selectedMark - for example, by using the id of the first item.

async mounted() {
  this.items = await axios
   .get("http://local/api/sd/make/get")
   .then(response => response.data.data.items);
  
  if (this.items.length) {
    this.selectedMark = this.items[0].id;
    const id = { id: this.selectedMark };
    await axios
      .post("http://local/api/sd/model/get", id)
      .then(response => { this.info = response.data.data.items });
    this.selectedModel = this.info.length ? this.info[0].id : null;
  }
},

If you want to fetch new data each time a different item is selected, you'll need to create a function that is triggered on the change event.

<select v-model="selectedMark" @change="onchange">
    <option v-for="model in items" :key="model.id" :value="model.id">
      {{ model.name.value }}
    </option>
</select>

async onchange() {
  this.info = await axios
    .post("http://local/api/sd/model/get", { id: this.selectedMark })
    .then(response => { response.data.data.items });
  this.selectedModel = this.info.length ? this.info[0].id : null;
}

Don't forget to add the :value attribute to the option tags

Here's a working example BUT utilizing the JSON placeholder FREE REST API (for demonstration purposes)

Answer №2

To handle the selection change event, you can utilize the @change event and implement it within the Methods hook as shown in the example below.

<template>
  <main class="home-page">   
    <select v-model="selectedMark" @change="getInfo(selectedMark)">
        <option v-for="model in items" :key="model.id">{{ model.name.value  }}</option>
    </select>
    <br><br>
    <select v-model="selectedModel">
        <option v-for="make in info" :key="make.id" >{{ make.name.value }}</option>
    </select>
    <br><br>
    <button type="submit" class="conectButton">Connect</button>
    <div class="titleCarMain"><p class="titleCar">{{selectedMark}}</p><p class="titleComponent">{{selectedModel}}</p></div>
 </main>
</template>

<script>

import axios from 'axios';

export default {
  name: "App",
  data() {
      return {
        info: null,
        items: [],
        selectedMark: null,
        selectedModel: null,
      };
  },
  created() {
    this.getItems()
  },
  methods: {
    getItems() {
        axios
        .get("http://local/api/sd/make/get")
        .then(response => { this.items = response.data.data.items });
    },
    getInfo(selectedMark) {
        await axios
        .post("http://local/api/sd/model/get", selectedMark) //does not work 
        .then(response => { this.info = response.data.data.items });
    },
  }
};

 

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

Getting information from PHP through AJAX for transmission to a separate PHP script

Hi everyone, I'm facing a bit of a challenge with my project. Here's the situation: I've got a PHP file that interacts with a database and displays the query results. Then, there's an HTML file that uses AJAX to show these results dyna ...

The onload function for a JSP embedded in an IFrame was causing the IFrame to expand and fill the entire browser

I am encountering an issue with an IFrame inside a DIV where the SRC attribute is being dynamically set by a JavaScript function. When the SRC is set to "file.jsp", an onload function within the file.jsp containing style adjustments was causing the IFrame ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...

Error: Attempting to create a Discord bot results in a TypeError because the property 'id' is undefined

While working on a basic Discord bot, I encountered an issue when running the -setcaps command. The error message I received was: TypeError: Cannot read property 'id' of undefined. I'm unsure about what might be causing this error. Any a ...

Convert a string with the characters '"' retrieved from a MySQL database into JSON

After creating a JSON object and storing it in MySQL, I encountered an issue when trying to retrieve and parse it. When I stringify the JSON object, the properties are being enclosed in double quotes causing issues when parsing the retrieved string. Below ...

Styling the elements that are next to each other using CSS

Hey there, what if I have HTML elements structured like this: <div> <div>Name</div> <div><input type="text" class="check"> <div>Age</div> <div><input type="number" class="check"></div> ...

What is the best way to display items using Typeahead.js in combination with the Bloodhound engine?

I am struggling to showcase a collection of items using typeahead with a JSON file as the data source. Unfortunately, none of my information is appearing on the screen. My objective is to list the names and utilize the other attributes for different purpo ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

Tips for correctly cloning a table row:

Currently, I am engaged with a Django project that involves incorporating a form within a table structure. <table name="mytable" id="table_purchase" role="grid"> <thead> <tr> <th class="text-center" hidden>No</th& ...

Angular routes are failing to update the view even after attempting to refresh

I am facing an issue while trying to develop an angular app where the child state is not loading properly. app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('home& ...

What is the best way to invoke a function within an AngularJS controller?

Currently, I am exploring the most efficient method of calling a function from an AngularJS controller externally. In our setup, data is transmitted from a Python backend to the frontend using JavaScript functions. To feed this data into the Angular contr ...

Finding and removing an element using Jquery

$.ajax({ type: "GET", url: "ajax/getLinks.php?url=" + thisArticleUrl }).done(function (data) { var extractedContent = $(data).find("#content > div > div.entry.clearfix"); extractedContent.find("#content > di ...

Is it possible to include two functions within a single HTML script?

On my webpage, there are multiple tabs that display different sets of data. Below is the code for handling the functionality of these tabs: function openTab(event, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassNa ...

Dynamically filling a second dropdown menu according to the selection made in the first dropdown using AJAX and PHP

Help! I'm feeling a bit overwhelmed. Even though this question has been answered multiple times, I still can't figure it out. There must be something so obvious that I am missing. I want the options in the second select input to be populated dyn ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Is there a way to determine if a file is an audio or video file using Vue.js by examining its URL?

I am currently working on a Vuetify playlist that contains a mix of audio and video media files. My goal is to create functionality that allows me to launch a video player if the file is a video, or utilize the html5 audio component for .mp3 files: ...

What is the best way to navigate users to a different page using AJAX upon receiving a successful response from PHP?

I am currently using a JavaScript function that is functioning correctly. It retrieves all error messages from the PHP file and displays them in a span with the ID "resto" without any issues. However, I now have a requirement where if the PHP file return ...

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

Updating the state of a React Component using data from 2 input fields

I am facing an issue with two input fields of type "file" in a React component. My goal is to load a JSON file into each input field, save the data from both files into separate variables, and update the state of the component. However, I have noticed that ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...