Perform an AJAX request to validate the delete action before finalizing it

My website features a Telerik grid, which essentially represents a table on a page.

Within this Telerik grid, there is a column dedicated to deleting records. Initially, when a user clicked on the delete link, a javascript confirm dialog would pop up. If the user confirmed deletion by pressing "OK", the code would proceed to delete the record; if not, the process would be cancelled without refreshing the page. The original code for this functionality is provided below:

    columns.Template(
                @<text><a href='@Url.Content("~/HazardControl/Delete/" + @item.Id)' 
style="cursor:pointer;" onclick = "return confirm('Are you sure you want to delete this record?');">
                    <img src="~/Content/Images/DeleteItem.gif" alt="Delete" />
                </a></text>
            ).Width(50).HtmlAttributes(new { style = "text-align:center" });

The current requirements necessitate a check to determine if a record is eligible for deletion before prompting the confirmation message. As a result, my updated code now looks like this:

    columns.Template(
                    @<text><a href='@Url.Content("~/Training/Delete/" + @item.Id)' 
style="cursor:pointer;" onclick="deleteConfirmation(@item.Id)">
                        <img src="~/Content/Images/DeleteItem.gif" alt="Delete" />
                    </a></text>
                ).Width(50).HtmlAttributes(new { style = "text-align:center" });    

    <script type="text/javascript" >
            function deleteConfirmation(recordId) {
                $.ajax({
                    url: '@Url.Action("ValidateDelete", "Training")',
                    type: 'POST',
                    data: { id: recordId },
                    success: function (result) {
                        var deleteRecord = false;
                        if (result) {
                            var userConfirm = confirm('Are you sure you want to delete this record?')
                            if (userConfirm) {
                                deleteRecord = true;
                            }
                        }
                        else {
                            alert('Deletion not allowed, the record is in use!');
                        }
                        return deleteRecord;
                    }
                });
                return false;
            }
        </script>

Although I attempted to handle this validation process using an AJAX call before triggering the confirmation dialog, the issue remains that the link still activates regardless of whether "true" or "false" is returned. My understanding was that returning "false" using the anchor tag's onclick method should prevent any action, but it seems different with AJAX. What could I possibly doing wrong here? Has anyone encountered and resolved this situation before? Is it feasible to achieve this scenario?

Answer №1

When making an AJAX call, it operates asynchronously which means that regardless of whether you return true or false, it will not impact event bubbling.

In the scenario outlined below, returning true triggers a click event on the original element, leading to a true response and enabling the link click action. If there are multiple links, you may need to rename the deleteRecord variable, and the #linkid should correspond to the initially clicked element. If you have assigned an id to the link like

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2e2f262f3e2f033e2f27670a233e2f2764032e">[email protected]</a>
, you can reference this in your JavaScript code.

var deleteRecord = false;

function deleteConfirmation(recordId) {
    if(!deleteRecord)
    {
        $.ajax({
            url: '@Url.Action("ValidateDelete", "Training")',
            type: 'POST',
            data: { id: recordId },
            success: function (result) {
                if (result) {
                    var userConfirm = confirm('Are you sure you want to delete this record?')
                    if (userConfirm) {
                        deleteRecord = true;
                        $("#linkid").click();
                    }
                }
                else {
                    alert('Delete not allowed, the record is in use!');
                }
            }
        });
    }
    return deleteRecord;
}

Answer №2

My method involved removing the link and assigning the OnClick event to the image. Javascript was utilized to perform the necessary checks and execute calls to delete the link.

columns.Template(
            @<text>
                <img src="~/Content/Images/DeleteItem.gif" alt="Delete" style="cursor:pointer;" onclick="deleteConfirmation(@item.Id)" />
            </text>
        ).Width(50).HtmlAttributes(new { style = "text-align:center" });
<script type="text/javascript">
    function deleteConfirmation(recordId) {
        $.ajax({
            url: '@Url.Action("ValidateDelete")',
            type: 'GET',
            data: { id: recordId },
            success: function (result) {
                if (result) {
                    var userConfirm = confirm('Are you sure you want to delete this record?')
                    if (userConfirm) {
                        window.location.href = '@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()/Delete/' + recordId;
                    }
                }
                else {
                    alert('Delete not allowed, the record is in use!');
                }
            }
        });
    }
</script>

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

Obtaining the selected date value from a Vue.js datepicker

How can I calculate the difference in days between two selected dates in Vue.js before the form is submitted? I want to provide a price based on this calculation. I am using a Persian date picker, which you can find here: https://github.com/talkhabi/vue- ...

I encountered an issue while using mediaRecorder to save a JavaScript animation; the blob value returned as null

My current project involves using Vanta js to create an animated background and mediaRecorder to capture the canvas as a webm file. The recording process is supposed to start from the beginning and stop after 1 second, exporting the webm file. However, I ...

Ways to create a URL path that is not case-sensitive in NextJs using JavaScript

I am currently working on a project using NextJs and I have encountered an issue with URL case sensitivity. The paths fetched from an API all start with a capital letter, causing inconsistency in the URLs. For instance, www.mysite.com/About. I would like t ...

Is it possible for me to nest a Firebase collection within another collection?

When gathering user information and favorite foods in a form, I'd like the favorite food data to be nested under the 'users' collection as Likes: const sendPosts = (e) => { e.preventDefault() db.collection("users").add({ ...

Strategies for finding additions and deletions in two arrays using Node.js

Looking for a solution to compare two arrays that are subject to change periodically. The aim is to identify the additions and deletions between the original array and the updated array. Changes can occur at any point within the arrays, not just at the be ...

Can we pass a search term parameter to getServerSideProps in Next.js?

I've been working on a project to organize all my notes and summaries in one place. The notes are stored as markdown files, converted to HTML dynamically in the backend (it's functioning well). Now, I want to add a search feature on the notes p ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

Navigating through React Native with TypeScript can be made easier by using the proper method to pass parameters to the NavigationDialog function

How can I effectively pass the parameters to the NavigationDialog function for flexible usage? I attempted to pass the parameters in my code, but it seems like there might be an issue with the isVisible parameter. import React, { useState } from 'rea ...

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

How to retrieve MySQL datetime values in PHP?

Currently, I am working on a countdown timer using PHP and JavaScript. The main issue I am facing is trying to retrieve the datetime ($end_date) from MySQL and inserting it into the $date ='' within my code. The code functions correctly when I m ...

Headers with a 3 pixel stroke applied

I have a design on my website that includes a 3px stroke around the header text to maintain consistency. I don't want to use images for this due to issues with maintenance and site overhead. While I know about the text-stroke property, browser suppor ...

Compare the selected values of radio buttons with an array and find matches

I have multiple radio button groups, where each selection in a group corresponds to predefined values in an array. For example, selecting option 1 in Group 1 will increment values A and B by 1, while selecting option 2 will increment B, C, and D. The goal ...

Show information from a table row within a modal box using Bootstrap 4

Is there a way to show table row td data in a Bootstrap 4 modal after clicking on the show data link? Here is the HTML structure: <table class="table table-bordered"> <tbody> <tr> <td data-title=& ...

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

Using React Router to send selected component to parent element

The content of App.js includes the following; render() { return ( <div className="App"> <Navbar /> </div> ) } Meanwhile, in Navbar.js class Navbar extends React.Component { render() { ret ...

Tips for incorporating dimensions from ajax svg text with jquery:

When receiving SVG content through AJAX jQuery, the width and height are missing. To solve this issue, we can add the width and height from the AJAX jQuery response. Code: $jd.ajax({ type: "POST", data: item, ...

React-Native has reached the maximum update depth, please check the new state

When I try to add and change the number (setNum(number+1)), I encounter an error message stating: Maximum update depth exceeded. This issue may arise when a component repetitively calls setState inside componentWillUpdate or componentDidUpdate. React enfor ...

What is the best way to showcase my React App.js in an HTML document?

Is there a way to display my React app file (App.Js) within my Index.html file? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/fav ...

What are some debugging techniques for troubleshooting jQuery.post() requests when using JSON as the dataType?

Despite my efforts to rely solely on the search function, I am faced with an issue that I can't seem to resolve: Using jQuery, I call a PHP script to fetch values which are then used to update my HTML elements. Here is a snippet of my code: $.post( ...