:onchange event triggering iteration through a function

My Vue.js application is experiencing issues with infinite post requests when a selectbox value changes. I have a table component that needs to display students from different 'tutorgroups'. Each tutorgroup, like '4M07a', has its own set of students. To achieve this, I am using an :onchange event in my selectbox to trigger a method which sends the selected value along with other data via Axios post request. However, the onchange event seems to cause a loop in the method, as observed in the network tab of DevTools where unlimited requests are being made. Can someone help me resolve this problem?

I have attempted using various event handlers and adding a return statement in my method without success.

Selectbox code snippet:

<select v-model="selectedValue" @change="getStudents(this.selectedValue)" class="select-klas form-control">
    <option> Select a tutorgroup </option>
    <option v-for="(tutorklas, index) in tutorklassen" :key="index">{{ 
    tutorklas.id }}</option>
</select>

Method code snippet:

getStudents(event) {
            // prepare data to be sent
            const postTutorClassData = new FormData();
            postTutorClassData.append('teacher', this.teachername)
            postTutorClassData.append('apikey', this.apikey)
            postTutorClassData.append('tutorgroup', event)

            // make post request to API
            axios.post(this.URL_TUTORKLAS, postTutorClassData)
            .then((response) => {
                this.teachers = response.data.teacher;

                this.students = response.data.students;

                // force stop
                this.selectedValue = 'null';

            })
            .catch(function (error) {
                console.log(error);
            });
        },

No error messages are displayed, just an endless loop in the method execution.

Answer №1

:onchange is not the correct syntax for detecting a change event in Vue. Additionally, there is no need to pass this.selectedValue into the method as it is already available in your data (remember that you cannot access this within a template).

Consider the following changes:

Replace :onchange with:

@change="getStudents"

Modify your getStudents method to:

getStudents() {
    const postTutorClassData = new FormData();

    postTutorClassData.append('docent', this.teachername);
    postTutorClassData.append('apikey', this.apikey);
    postTutorClassData.append('tutorgroep', this.selectedValue) // remove event and use selected value

    axios.post(this.URL_TUTORKLAS, postTutorClassData).then(response => {
        this.docenten = response.data.docent;
        this.leerlingen = response.data.leerlingen;

        // this.selectedValue = 'null';
        // Changing this to null will trigger the change event again, potentially causing an infinite loop
    }).catch(function (error) {
        console.log(error);
    });
},

Answer №2

replace :onchange with @change

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

Tips for effectively utilizing an autocomplete input field with Vue that draws information from a database source

I am looking for a way to implement an autocomplete feature in my Vue application using data from a database table with over 3000 records. Here is how I am currently retrieving the data: data(){ return{ inboundRelation_Trelation_data: [], } ...

Challenges encountered when uploading files

Within my react form, I have multiple files that are uploaded to be sent to the backend. Below is a snippet of code for the form submit button: const handleSubmit = async (e) => { e.preventDefault(); setDisabled(true); const ...

Vue: Opening all GmapInfoWindows simultaneously upon clicking one

I am working on a platform where users can report crimes or incidents by placing markers on a map. These markers with all the reported incidents are then displayed on another map. Each marker has an info window that provides details about the incident and ...

Developing an SQL table for a website using JavaScript

My command is not functioning as expected and I am struggling to identify the issue. The database opens successfully, however, it fails to process the table creation. var createtable2 = 'CREATE TABLE IF NOT EXISTS offlineCabinDefects (id INTEGER PRIM ...

Is there a way for me to determine if something is hidden?

My goal is to have selector B toggle when selector A is clicked or when clicking outside of selector B. This part is working fine. However, I'm struggling with preventing selector B from toggling back unless selector A is specifically clicked - not w ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

converting code from JavaScript to Flask and then back to JavaScript, all within a single-page application

In order to make my single-page web app fully functional, I have completed the following tasks: Sent a json from .js to Flask (COMPLETED) Ran the input through a Python function called getString() and obtained a string output (COMPLET ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

Issue with ion-content on Ionic app not scrolling down when keyboard is displayed on an Android device

Currently, I am facing an issue with a basic view that contains a login form. When the keyboard pops up on Android devices, the content does not scroll up to ensure it remains visible above the keyboard. I have diligently followed the Keyboard instruction ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

Tips for featuring the latest blog post at the top of a NextJS blog

I have a website built on Next JS with a blog page. The setup is correct, where the /blog page displays content based on slugs. Currently, new blog posts are appearing at the bottom of the page, under older ones. I want to reverse this so that when a new p ...

Experience the convenience of Visual Studio Code's auto-completion feature for HTML tags even when working within an

My HTML file has a babel script embedded within it. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React tutorial</title> <script src="https://unpkg.com/react@16/umd/react.development.js" ...

Send location data to the PHP server through AJAX and then fetch it in JavaScript once it has been handled

I am looking to transfer coordinates from client-side JavaScript to server-side PHP using Ajax, and then retrieve the processed result back to JavaScript for further use. While I have managed to pass the data to PHP successfully, I am struggling to figure ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

Unlock the full potential of knockout.js by mastering how to leverage templates recursively

Given the following model and view model for nested categories: function Category(id, name) { var self = this; self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000'); self.Name = ko.observable(name); self.children ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

Submitting data twice through AJAX POST requests

Using a PHP file called via AJAX to insert data into MySQL. Prior to the insert statement, the PHP code runs a select query to check for duplicate records and then proceeds with the insert statement. Problem: When calling the PHP file from AJAX, it gets ...

The React Js error message shows an 'Uncaught (in promise)' TypeError that prevents reading an undefined property

Struggling with passing the response from an Ajax request to another function in React. Although I am able to receive the response, I cannot pass it to { this.showBattersData(data); } where I need to render the DOM. It's clear that something is missin ...

Simple Steps for Making a Get Request using Vuex in Vue.js

I'm trying to figure out how to store products in Vuex within my index component. import Vue from 'vue' import Vuex from 'vuex' import cart from "./modules/cart"; import createPersistedState from "vuex-persistedstate ...