Stopping Default Behavior or Button Click Event in JavaScript During Ajax Request

I've utilized e.preventDefault() previously to stop a click event, but I'm struggling to understand why it's not functioning in this particular case. I've assigned all anchor tags in a column a classname, then obtained references to them using

document.queryselectorAll(.classname)
. For each anchor tag, I've added a click event that retrieves values from the server, and if validation criteria are not met, it should prevent the default action and display a message to the user.

(function(){
const userName = document.getElementById('FullName').value;

// route
$route = '';
if (CheckDeploy(window.location.origin)) {
    $route = '/x/GetReviewerCheck/';
} else {
    $route = '/servername/s/GetReviewerCheck/';
}

let ReviewButtons = document.querySelectorAll('.verifyReviewer'); // .verifyReviewer = className of all anchor tags in table column

for (var i = 0; i < ReviewButtons.length; i++) {
    const ReviewButton = ReviewButtons[i];
    ReviewButton.addEventListener('click', function (e) {
        let newRow = ReviewButton.parentElement.parentElement;
        let AuditorName = newRow.cells[2].innerText;
        let ReviewType = newRow.cells[8].innerText;

        let ReviewTypeID = 0;
        if (ReviewType == 'Peer Review') {
            ReviewTypeID = 3;
        } else if (ReviewType == 'Team Leader Review') {
            ReviewTypeID = 4;
        }
        else if (ReviewType == 'Supervisor Review') {
            ReviewTypeID = 5;
        }

        let id = newRow.cells[0].firstChild.getAttribute('id').split('_')[1];

        $.ajax({
            url: $route,
            type: 'POST',
            data: { userName: userName, auditor: AuditorName, reviewType: ReviewTypeID, recordID: id },
            success: function (data) {
                // if data is 1, prevent default
                if(data == 1){
                    e.preventDefault();
                    return false;
                }
            }
        });

    }, false);
}
})();

Answer №1

There seems to be an issue with the functionality due to the asynchronous nature of the response. The e.preventDefault() method will only be triggered once the ajax call receives a response from the server. To address this, you can follow these steps:

  1. Prevent the default action for all actions initially.
  2. Wait for the response to be received.
  3. If the response is not equal to 1, then unbind the preventDefault() method.

Modifications have been made to the for loop, and comments explaining the changes have been added. Please review the updated code accordingly.

for (var i = 0; i < ReviewButtons.length; i++) {
        const ReviewButton = ReviewButtons[i];
        ReviewButton.addEventListener('click', function (e) {
            let newRow = ReviewButton.parentElement.parentElement;
            let AuditorName = newRow.cells[2].innerText;
            let ReviewType = newRow.cells[8].innerText;

            let ReviewTypeID = 0;
            if (ReviewType == 'Peer Review') {
                ReviewTypeID = 3;
            } else if (ReviewType == 'Team Leader Review') {
                ReviewTypeID = 4;
            }
            else if (ReviewType == 'Supervisor Review') {
                ReviewTypeID = 5;
            }

            let id = newRow.cells[0].firstChild.getAttribute('id').split('_')[1];

            $.ajax({
                url: $route,
                type: 'POST',
                data: { userName: userName, auditor: AuditorName, reviewType: ReviewTypeID, recordID: id },
                beforeSend:function()
                {
                    e.preventDefault(); //Prevent default action for all instances.
                },
                success: function (data) {
                    // if data is 1, prevent default
                    if(data != 1){
                        $(this).unbind('click'); // Restores the default click behavior if data is not equal to 1
                        return false;
                    }

                }
            });

        }, false);
    }

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

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

Callbacks in Laika tests go untriggered

Meteor.collection.insert() allows for the use of a callback as one of its arguments. To demonstrate, you can start a new Meteor project and execute the following code in the browser's console. my_collection = new Meteor.Collection("myCollection"); my ...

Exploring JSON array handling with jquery

Here is the JSON data I am working with: { "category": { "category_identification": "1", "category_name": "C1", "image_one": "1.PNG", "image_two": "1_.PNG", "logo": "LOGO_1.PNG", "category_description": "DESCRIPTION" }, "responseCo ...

Tips for retrieving multiple objects from an ajax request in Grails

Currently, I am facing an issue with my ajax function as it is expected to send back a list of objects. Please forgive me for this question, as I am still new to Grails and web programming. Just to give you an idea, my ajax function is supposed to combine ...

Refreshed page causing hide/show div to reset

Hello there, I'm currently working on a web application and I need to implement some JavaScript code. The application consists of three sections, each with its own title and button. When the button is clicked, a hidden div tag is displayed. Clicking t ...

Start by executing the function and then proceed to upload a static file

Here is the code I am working with: var express = require('express'), app = express(); app.use(express.static(__dirname + '/static')); app.get('/', function(req, res) { //??? }); app.listen(80); I need to first ex ...

Is it possible to change the transition behavior within a Vue component?

Is there a way to modify or replace transitions within a Vue component? I am currently using Buefy components for my website, but I have encountered an issue with certain components like collapse that have a slot with a fade transition that I do not pref ...

Failure to Present Outcome on Screen

Seeking assistance! I attempted to create a mini loan eligibility web app using JavaScript, but encountered an issue where the displayed result did not match the expected outcome upon clicking the eligibility button. Here is the HTML and JavaScript Code I ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

"Trying to access jQuery .slide and .slideUp features, but unfortunately they are

I've created this script: $("#comments .comment .links").hide(); $("#comments .comment").hover( function() { $(".links", this).stop(true).slideDown(300); }, function() { $(".links", this).stop(true).slideUp(300); } ); However, I'm facin ...

Having trouble retrieving data from AJAX into the controller. The error message reads: "Undefined index: dataId."

Whenever I click a button with an id, I want it to redirect me to a specific page based on its id. However, I encountered an error stating "undefined index: dataId" Below is the ajax code: $(document).ready(function(){ $(".btn-clinic").click( ...

The jQuery ajax request was unsuccessful in connecting to the remote server

I've tried researching and troubleshooting, but I still can't figure out why the Ajax code is not functioning correctly. Here is my JavaScript code: $(document).ready(function(){ $("#tform").submit(function() { var varUserName ...

The user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

Trigger callback function when user selects a date on the calendar using Material UI X Date Picker

I am currently utilizing the DateTimePicker component in material ui, version 5. I am looking for a way to intercept the callback triggered when a user clicks on a day in the calendar selector: https://i.stack.imgur.com/0Tlogm.png Although the DateTimePi ...

The functionality of Material UI Slider components becomes less responsive when enclosed and rendered in JSX

Why is the Material UI's Slider not working smoothly when called in JSX as shown below? SliderAndValue.js import { Slider } from "@material-ui/core"; import { useState } from "react"; import "./styles.css"; export const ...

Refresh a specific DIV element without having to refresh the entire page

I have a Div Tag that includes Small.php to populate it with information. My goal is to refresh the content every 15 seconds without reloading the entire webpage. I've attempted using JavaScript/jQuery without success. <script type="text/javascrip ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

Performing a sequence of actions using Jquery Queue() function and iterating through each

I am facing an interesting challenge with an array called result[i]. My goal is to iterate through each field in the array and add it to a specific element on my webpage. $("tr:first").after(result[i]); However, I would like this process to happen with a ...