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

Having issues with function arguments and parameters not functioning correctly in a Vuetify project when utilizing the "this" keyword?

In my current Vuetify project, I am trying to achieve a similar functionality as shown in the following plain HTML/JavaScript example: <body> <button id="anid" onclick="idcheck(this.id)"> </button </body> <script> function ...

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

Ensure to close the Ajax request from PHP before the script finishes executing

Is there a way to terminate an Ajax request from PHP before the script finishes executing? For instance, if a user requests php.php and it includes the line 'echo "phpphp"', how can we ensure that the Ajax request is completed with the data "phpp ...

Utilizing CSS to Display a Variety of Colors within a Text String

Is it possible to style different words in a sentence with various colors using only CSS, without using the span element? For instance, how can I make the word "Red" appear in red, "Blue" in blue, and "Green" in green within an h1 tag? ...

The local authentication feature in NodeJS Passport is experiencing issues and not functioning properly

I have integrated passportjs local for authentication. However, I am facing an issue where it always redirects to the failureRedirect without displaying any error messages. The redirect also includes the original username and password, resulting in a dupli ...

Update a div in PHP using the data received from an AJAX response

I recently developed a PHP application and encountered an issue with updating the value of a date picker. The user is prompted for confirmation when changing the date, and upon confirmation, the date in the "expiry" field (with id expiry) should update alo ...

Is it possible for a JWT generated using RS256 to be decoded on the jwt.io platform?

After setting up my first Express server and implementing user authentication with jwt, I'm now searching for a method to encrypt the jwt in order to prevent users from viewing the payload on the website. I am curious if anyone is aware of an encryp ...

What are the steps to storing numerical inputs as variables using jQuery and then using them to perform calculations in order to update the input numbers

Currently, I am in the process of creating a BMI calculator using HTML and jQuery. <form id="bmiCalculator"> <fieldset> <legend>BMI Calculator:</legend> <p> <label>Height: ...

Using Next Js for Google authentication with Strapi CMS

Recently, I've been working on implementing Google authentication in my Next.js and Strapi application. However, every time I attempt to do so, I encounter the following error: Error: This action with HTTP GET is not supported by NextAuth.js. The i ...

What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript. The array I am working with is as follows: var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"]; My goal is to delete every second and ...

Run a PHP script on the current page upon choosing an option from a dropdown list with the help of Ajax or JavaScript

I'm currently working on a MySQL query that needs to be executed when a user selects options from multiple dropdown lists. What I am looking for is the ability to automatically run a query related to the selected dropdown list option using AJAX/JavaS ...

Using Ramda, learn how to transform a flat list into a hierarchical one

Looking to transform the given list into a hierarchical structure with nested children fields. The 'parentId' attribute has been omitted for clarity, as it will be used in the transformation process using Ramda's immutable behavior. const x ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

JQuery does not recognize $(this) after the HTML has been altered

I manage a website that includes several href links and 2 buttons that have the ability to modify those links dynamically. <div class="links"> <p class="hlCategory">Classical Mechanics</p> <ul> <li><a cl ...

Tips for customizing Material-UI Switch button appearance

Is there a way to remove the box-shadow on the thumb of the Switch button when it's disabled? I've tried various methods like adding the box-shadow in the switchBase and removing it from the thumb, but it affects the parent element as well. Anoth ...

Storing a function value in a variable within a Node.js server to retrieve folder size

I have been searching for a way to determine the size of a folder's contents and discovered that using the get-folder-size package is the best option. The code snippet below explains how to achieve this: const express = require('express'); ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Retrieving the chosen option from a dropdown menu without the need for a page

Currently, I am facing an issue with the view limit dropdown on my page that contains multiple filters for searching data from a Database. At the bottom of the page, there is a view limit dropdown separate from the main search form. This dropdown allows us ...