Prevent Default Behavior or A Tag Click Event in JavaScript Inside Ajax Call

前端 未结 1 1902
面向向阳花
面向向阳花 2021-01-19 09:28

I have used e.preventDefault() in the past to cancel a click event, but I am having trouble figuring out why it isnt working in this scenario. I assigned all a

相关标签:
1条回答
  • 2021-01-19 10:12

    It's not working because, the response is asynchronous. e.preventDefault() will be executed only after ajax call gets a response from the server. You can do this.

    1. Prevent Default action for all actions.
    2. Wait for response.
    3. If response is not 1 then unbind the preventDefault().

    I have updated the for loop, and commented the changes. Kindly do check.

    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 click default behaviour if data != 1
                            return false;
                        }
    
                    }
                });
    
            }, false);
        }
    
    0 讨论(0)
提交回复
热议问题