Issues with C# asp.net Confirmation Functionality in Asynchronous Ajax Request

Greetings in advance, I am diving into the world of JavaScript for the first time. The code snippets provided below have been crafted after seeking guidance from various sources.

My aim is to utilize a webmethod that detects if a page has undergone modifications and returns a boolean value:

<script type="text/javascript">
    function OnConfirm() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "UserManagement.aspx/IsDirty",
            dataType: "json",
            data: '{}',
            success: function OnDirtySuccess(result) {
                if (result.d.toString() == "true") {
                    return confirm("You have unsaved changes, select OK to discard these changes without saving.");
                }
                else {
                    return false;
                }

                return true;
            },
            failure: function (response) {
                return true;
            }

        });
    }
</script>

A button triggers the execution of this script:

<asp:Button ID="btnAddNewUser" CausesValidation="false" runat="server" Text="Add New User" OnClick="btnAddNewUser_Click" OnClientClick="return OnConfirm();" Width="140px" />

The method call is functioning correctly as I only receive the confirmation dialog when the current user has been modified. However, my concern arises when clicking 'cancel' as the btnAddNewUser_Click event still gets triggered.

I attempted an alternate approach based on another question, but encountered issues:

<script type="text/javascript">
    function OnConfirm() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "UserManagement.aspx/IsDirty",
            dataType: "json",
            data: '{}',
            success: function OnDirtySuccess(result) {
                if (result.d.toString() == "true") {
                    if (!confirm("You have unsaved changes, select OK to discard these changes without saving."))
                        return false;
                    //return confirm("You have unsaved changes, select OK to discard these changes without saving.");
                }
                else {
                    return false;
                }

                return true;
            },
            failure: function (response) {
                return true;
            }

        });
    }
</script>  
<asp:Button ID="btnAddNewUser" CausesValidation="false" runat="server" Text="Add New User" OnClick="btnAddNewUser_Click" OnClientClick="if (! OnConfirm()) return false;" Width="140px" />

In this revised snippet, I adjusted the OnClientClick to `if (! OnConfirm()) return false;` while also trying both versions of the confirm action within OnConfirm(). Unfortunately, even after choosing 'cancel' on the confirm dialog, the OnClick event persists.

A simplified test was conducted by altering the OnClientClick function to:

<script type="text/javascript">
    function OnConfirm() {
        return confirm('Test ok/cancel?');
    }
</script>

Here, the ok/cancel functionality of the confirmation dialog worked seamlessly.

What could be causing the issue with my OnConfirm function?

Answer №1

Take a look at this link, which provides the solution to your query

click here

Here's an update for you.

Make sure to use the POST method when passing data:

<asp:Button ID="btnAddNewUser" ClientIDMode="Static" CausesValidation="false" runat="server" Text="Add New User" Width="140px" />

Additionally,

<script type="text/javascript>
    $(function() {
        $('#btnAddNewUser').click(function(e) {
            e.preventDefault();
            // Perform ajax call
            var params = {};
            params.parameter = "passing string data";
            $.ajax({
                type: "POST",
                url: "YourPageName.aspx/MyFunction1",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(params),
                success: function(res) {
                    alert(res.d);
                },
                error: function(res) {
                }
            });
        });
    });
</script>

And don't forget to update YourPageName.aspx.cs file as follows:

[WebMethod]
public static string MyFunction1(string parameter)
{
    return parameter;
}

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

Here is a step-by-step guide on extracting a specific field from a JSON object obtained through an AJAX call to the Facebook Graph

I've been attempting to extract specific field values from a JSON object retrieved from the Facebook Graph API using an AJAX call in JavaScript. The code I'm utilizing to access the cover field from the JSON object is not providing the desired r ...

Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors. Looking to switch components using v-if and passing different properties. Here's a small example: Currently, when switching from 'blue' to 'red ...

Having trouble establishing an HTTPS connection with a Node.js server

After connecting to my server through the console without any errors, I encountered an issue in Chrome where it displayed a message stating This site can’t provide a secure connection local host uses an unsupported protocol. Here is the code snippet: im ...

Tips for performing a jQuery search on an element that is initially hidden

I have a div with a class name 'form'. Initially, this div is hidden (it's an asp.net web forms Panel control). The panel becomes visible when a search button is clicked to open a search form on the page. I want to detect when the user press ...

Angular ng-boostrap modal automatically refreshes upon detecting mouse movement with an embedded video

Currently, I am facing an issue with my Angular 7 ng-bootstrap modal. The problem arises when the modal, which includes a video player within an <iframe>, is moved to the production system. Whenever there is any mouse movement detected, the video get ...

Steps for Setting Up and Organizing a Fresh Event

My goal is to generate new events (using document.createEvent() or Jquery.Event) by duplicating all essential attributes, and then sending the clone to prevent alterations to the original event. For reference, the source code can be found at http://jsfid ...

Ways to incorporate encoded HTML text into string literals

When attempting to insert a HTML encoded special character within a string literal, I am encountering an issue where it does not display as intended in the final document. The approach I am taking is as follows: const head = { title: `${ApplicationName} ...

Issue with having Clipboard.js function not properly executing within the jQuery.get() method's done

My goal is to perform certain actions when the user clicks a button: Retrieve data from the server using jQuery AJAX. Upon success, assign this data as the value for the button's attribute data-clipboard-text. Copy this value to the clipboard using ...

Error message encountered on localhost: preflight response contains Access-Control-Allow-Headers issue

I'm currently working on my React app locally at localhost:3000 and utilizing this code snippet: try { const response = await fetch('https://myendpoint.com/abcd/search?c=abc123', { headers: { 'Content-Type': 'application ...

How to effectively implement console.log with JavaScript using Selenium in Python

My attempts so far: driver.execute_script("console.log('please help me see the console output')") Unfortunately, I did not get any results. ...

Retrieving user profile upon login using AJAX and PHP

I need to implement a way to fetch user profile data using AJAX and PHP upon login, without refreshing the page. Below is my login.php code. Once the login is successful, I want to display an alert with the user's name and email. <?php inclu ...

The entry description function is not functioning properly when used with jGFeed

I have implemented jGFeed to extract data from an RSS Feed. Below is a snippet of the code I am using: $.jGFeed('http://feeds.bbci.co.uk/news/rss.xml', function(feeds){ // Check for errors if(!feeds){ ...

Improved method for categorizing items within an Array

Currently working on developing a CRUD API for a post-processing tool that deals with data structured like: { _date: '3/19/2021', monitor: 'metric1', project: 'bluejays', id1: 'test-pmon-2', voltageConditio ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

retrieve user control from parent master page in child page

I am working on a setup where the master page contains a user control, and the child page (Abc.aspx) is linked to that master page. The child page also has its own user control. My task is to access the master page's user control from the child page&a ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

create hyperlinks based on div clicks in HTML using JavaScript

Hey there! I'm working on a cool animation for my page that involves a star fade effect. After the animation, I want to open a link to another page on my site. Imagine I have 3 cards on my page, and when I click on any of them, I want the same animat ...

Encountering an InvalidElementStateException while trying to delete text using Selenium

When testing the web application, I encountered a scenario where confirmation is required before deleting a record. To address this, I developed a test case to input a valid reason for deleting the record. The code snippet for performing this task is out ...

Obtain the 'data' attributes from JSON data using AJAX

I am currently working on accessing all data from a JSON file that is provided by a movie database API. However, I am struggling to understand how to retrieve this data as the console log is showing me a "data is not defined" error. Below is the code I am ...

Using Express Router to serve and display static files in the public directory

The code snippet below is found in my index.js file: var express = require('express'); var app = express(); var PORT = 3000; var routes = require('./scripts/routes/routes'); app.set('views', './views'); app ...