Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receive an array of error messages in response. However, despite trying to prevent the form submission with e.preventDefault(), it does not seem to be working as expected.

Interestingly, when I use e.preventDefault() outside of the axios request block, the form submission is successfully prevented. This led me to believe that there might be a scope issue with the 'e' variable. So, I am wondering how I can extend the scope of the 'e' variable to make it work within the axios request?

Below is the code snippet causing the problem:

checkAvailability(e){
            let date = document.getElementById('date').value;
            let errorList = document.getElementById('errors');

            date = date.split('-').reverse().join('-');

            axios.get('/materials/check-availability', {
                params: {
                    date: date,
                    time: this.time,
                    ek: this.ekNumber,
                    dk: this.dkNumber,
                    ck: this.ckNumber,
                    zv: this.zvNumber,
                    ton: this.tonNumber
                }
            })
            .then(function(response) {
                let errors = response.data;

                if(errors.length > 0)
                {
                    e.preventDefault();
                    
                    errorList.innerHTML = '';

                    for(let i = 0; i < errors.length; i++)
                    {
                        let li = document.createElement('li');

                        li.innerText = errors[i];

                        errorList.appendChild(li);
                    }

                    errorModal.show();
                }
            })
            .catch(function(error){
                console.log(error);
            });

            // e.preventDefault();
        }

Answer №1

It's important to note that calling e.preventDefault() within a promise won't have the desired effect, as the default action will already have taken place by the time the promise is resolved (asynchronous).

To work around this, you should call preventDefault immediately upon form submission and then manually handle the form submission based on certain conditions. The code snippet below provides a basic example of how to achieve this:

handleFormSubmission(e){
        e.preventDefault();

        let date = document.getElementById('date').value;
        let errorList = document.getElementById('errors');
        const yourForm = document.querySelector('form');

        date = date.split('-').reverse().join('-');

        axios.get('/materials/check-availability', {
            params: {
                date: date,
                time: this.time,
                ek: this.ekNumber,
                dk: this.dkNumber,
                ck: this.ckNumber,
                zv: this.zvNumber,
                ton: this.tonNumber
            }
        })
        .then(function(response) {
            let errors = response.data;

            if(errors.length > 0)
            {
                
                errorList.innerHTML = '';

                for(let i = 0; i < errors.length; i++)
                {
                    let li = document.createElement('li');

                    li.innerText = errors[i];

                    errorList.appendChild(li);
                }

                errorModal.show();
            } else {
                yourForm.submit();
            }

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

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 could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

What could be causing my problem with the add function?

I'm having trouble capturing the user input from modal input boxes and adding them to my state array. I've attempted to extract the values from the inputs and push them into a clone of the state array, then update the state with the clone. Howeve ...

Unexpected results from the match() function

Attempting to utilize the RegExp feature in Javascript (specifically with the match function) to locate instances of a sentence and a specific word within that sentence embedded in the HTML body. Provided is some pseudo-code for reference: <!DOCTYPE ...

How to Use Google Tag Manager to Track Forms with Various Choices

Currently, I am facing a challenge in setting up conversion tracking using GTM for a form that offers users multiple options via a drop-down menu. When the user clicks on an option, they are presented with choices like A, B, C, and D. After selecting an ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Strategies for eliminating _next folder from file path within the build directory of Next Js

Is there a way to eliminate "_next" from the path in the build folder for Next Js version 13.2.4? For reference, here is an example: We would greatly appreciate any assistance on this matter. ...

Error sound produced when detecting KeyCode on the keyboard

I'm currently working on a JavaScript project that involves capturing keyboard input. However, I'm encountering an issue where every time the user presses a key, it triggers an error sound. Is there a way to disable this sound? ...

Assign a class to a DIV element depending on the ID of an object using Angular

I'm trying to dynamically add a class to a div based on the id of a field in an object. However, my code doesn't seem to be working as expected. Can someone help me debug this? <ng-container *ngFor="let item of cards"> <d ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

Executing a function in AngularJS using PHP

My current project involves an Angular application that needs to load a PHP page within the view. The setup is functioning properly, but I now require an Angular function to run after the PHP code has loaded. I am wondering about the process of calling an ...

What is the best method to organize HTML tables in Knockout by utilizing a Breeze navigation property?

Currently, I am utilizing Breeze.js to manage my data model within Knockout.js. This involves a simple view model with an adapter library for handling sorting tables on entity properties. The tables are sorted using tablesorter, along with a knockout bindi ...

How to utilize Vue method for accessing DOM elements

I'm working on a container with various elements like h1, p, etc. The container has a background and I'm trying to create a method to move it based on mouse coordinates. However, I'm facing an issue where the e.target is showing me ele ...

Experiment with the Users.Get function available in vk-io

I am having an issue with a create command: Ban [@durov] and I encountered an error. Here is how I attempted to solve the problem: let uid = `${message.$match[1]}` let rrr = uid.includes('@') if(rrr == true){ let realid = uid.replace(/[@]/g, &ap ...

How to add an element to an array with a function in ExtJS

I am looking to add an element to the drawnShapes array within the draw() function and the getDrawnShapesCount() function should return the total number of shapes drawn The drawnShapes variable represents an array of shapes Ext.define('Shape', ...

I'm encountering an issue where Bulma is taking precedence over the CSS of my Vue3

In my Vue CLI 3 project, I'm utilizing Bulma and have included the import in the 'index.js' file like so: import { createApp } from 'vue' import App from './App.vue' import router from './router' require('@ ...

Next.js fails to load TailwindCSS

I am in the process of developing an app using tailwindcss and next.js First, I started creating the nextjs app, then I executed these commands: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p Following that, I made adjustments t ...

Can we modify the styling of elements in Angular based on an object property?

I have a class named Task with the following properties: export class Task { name: string; state: number; } Within my component.ts file, I have an array of objects consisting of instances of the Task class (tasks). When displaying them in the tem ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...