Troubleshooting Issue: JavaScript Confirmation Message

Presently, I have set up a popup confirm box to display as shown below:

However, the issue is that I am unsure whether the user clicked 'OK' or 'Cancel'.

ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", "<script language='javascript'>confirm('Do u wanna change?');</script>", false);

My goal is to achieve the following functionality:

if (originalId != newId)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", "<script language='javascript'>confirm('Do u wanna change?');</script>", false);

If (user clicks Yes)
{
add some data to SQL
}
else
{
return;
}
}

Now, the question arises - how can I determine what option the user selected?

I attempted the following:

  1. I placed the code below in a folder1\jscrip.js file. Nevertheless, I am uncertain of how to call it due to the presence of an ajax update panel on the page, preventing me from using `ClientScript.RegisterClientScriptInclude` for referencing. This issue is discussed further at the 6th point in this link:

Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl(@"folder1\jscrip.js"));

function confirmation()
{
if(confirm("Are you sure?")==true)
return true;
else
return false;
}

Any suggestions and insights would be greatly appreciated. Thank you.

Functionality:

The scenario involves the user clicking a button labeled "Save first". Upon doing so, it checks the condition of "if (orignalId != newId)". If this condition holds true, the confirm box appears; otherwise, no confirm box is displayed. Subsequently, if the user clicks 'OK', certain values are inserted into the database; otherwise, nothing happens.

Additional Code:

protected void Page_Load(object sender, EventArgs e)
        {
if (!IsPostBack)
            {
            }
 else if (Label.Text != "")
            {
                Global.logger.Debug("Postback Happ, Label = " + Label.Text);
                Button2_Click(sender, e);
            }
        }

 protected void Button2_Click(object sender, EventArgs e)
        { if (orignalCsId != 0 && newCsId != 0)
                {
                    if (orignalId != newId)
                    {
                        Global.logger.Debug("Pop Up crossed1");
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", String.Format(CultureInfo.InvariantCulture, @"__doPostback('{0}', confirm('Your Data From iD1 will be populated in iD2?').toString());", Label.Text), true);
                    }
                    else if (Page.Request["__EVENTTARGET"] == Label.Text)
                    {
                        Global.logger.Debug("__EVENTARGUMENT1 = " + Page.Request["__EVENTARGUMENT"]);
                        bool userClickedOK = Boolean.Parse(Page.Request["__EVENTARGUMENT"]);
                        if (userClickedOK)
                        {
                            // Add some data to SQL.
                        }
                        else
                        {
                            return;
                        }
                        Label.Text = "";
                    }
                }
          }

Answer №1

If you opt to utilize a hidden field, you will still need to trigger a postback after the user closes the confirm box. However, instead of relying on a hidden field, you can leverage the second argument of __doPostBack() to send the return value of confirm() back to the server:

if (originalId != newId) {
    ScriptManager.RegisterStartupScript(this, GetType(), "ajax",
        String.Format(CultureInfo.InvariantCulture, @"
            __doPostBack('{0}', confirm('Are you sure?').toString());
        ", yourUpdatePanel.ClientID), true);
} else if (Page.Request["__EVENTTARGET"] == yourUpdatePanel.ClientID) {
    bool userClickedOK = Boolean.Parse(Page.Request["__EVENTARGUMENT"]);
    if (userClickedOK) {
        // Add some data to SQL.
    } else {
        return;
    }
}

In this logic, we compare the two IDs initially. If they differ, the script prompts for confirmation on the client side and relays the result back to the server by executing a startup script. On the client end, __doPostBack() ensures the postback is triggered after handling the blocking call from confirm(). Note that you can specify true as the last argument in RegisterStartupScript() to generate <script> tags automatically.

Furthermore, upon triggering a postback where an UpdatePanel serves as the event target, the ASP.NET mechanism refreshes solely that panel (or additional ones based on their UpdateMode). Thus, by invoking __doPostBack() with the relevant ClientID of the UpdatePanel, along with the confirmed response converted to a string, we streamline the process.

Upon reloading the page on the server front, our code gets executed once more. Assuming the identities of originalId and newId match during this cycle, the confirm box remains inactive (as ensured by the else if condition).

The arguments fed into __doPostBack() become accessible server-side through the request variables __EVENTTARGET and __EVENTARGUMENT. Upon verifying the event target as our designated UpdatePanel, we interpret the deserialized value of __EVENTARGUMENT via Boolean.Parse() to determine whether updating the database is warranted.

Answer №2

To ensure smooth processing on the server side, utilize a Hidden field within your webpage. When the user confirms or denies an action, adjust the Hidden field value accordingly - either to true or false.

function confirmAction()
{

    var decision = confirm("Are you sure you want to proceed?");
    if (decision)
    { 
        document.getElementById('HiddenField').value = "True";
    }
    else
    {
        document.getElementById('HiddenField').value = "False";
    }
}

Server-Side Validation

if (originalId != newId)
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", "<script language='javascript'>confirmAction();</script>", false);

    if (HiddenField.value == "True")
    {
        // Add data to SQL
    }
    else
    {
        return;
    }
}

}

Answer №3

While it may have been some time since this question was first asked, I wanted to share my input for anyone who is still on the lookout for a clear and straightforward solution. If you are in need of a client-side JavaScript popup to confirm actions like deleting an item from your database, one easy method I have discovered is by utilizing the OnClientClick attribute within your asp:button or asp:linkbutton in the HTML markup:

<asp:LinkButton Text="Delete" ID="DeleteProj" runat="server" CommandName="deleteproj" OnClientClick="return confirm('Are you sure?');" CommandArgument='<%# Eval("ProjectID") %>'/>

If the user clicks "no", they will be redirected back to the page; however, if they click "yes", the designated C# codebehind logic will be executed accordingly. This approach worked effectively for me.

Answer №4

When using ScriptManager.RegisterStartupScript, it can sometimes cause a popup to be blocked. However, by following the method outlined in the link below, you will be able to have full control over every click within a popup.

This particular popup does not require any ajax, javascript, jquery, or css tricks, yet still allows for complete control over its interactions.

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

Tips for locating a specific property deep within an array and pinpointing its exact location

Is it possible to use JavaScript to locate a property within an array that is nested within another array and return its "path"? Visualize a hierarchical group of nested arrays similar to this example: var bigBox = [ mediumBoxA = [ ...

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

Creating dynamic selection options in an HTML select tag using PHP

When retrieving category and sub-category information from an API json file, the API returns category objects with a "parent" attribute. Main category objects have a parent attribute equal to 0, and sub-category objects have the parent attribute equal to t ...

Attempting to optimize MVC3 functionality in various regions

After setting up a new MVC3 project, I created a folder called "area1" inside my controller. Next, I added a controller named abc.cs inside that folder: public class abc : Controller { // // GET: /abc/ public ActionResult Index() ...

What is the process for integrating Android Java code with Node.js code?

I have some code that I am trying to integrate with Node.js for Firebase notifications on my Android application. I found a blog post outlining the implementation here: The Node.js code listens to changes in my Firebase Database and triggers notifications ...

The Bootstrap carousel controls now add the carousel ID to the address bar instead of just moving to the next slide

I can't figure out why my carousel isn't working. The id of the carousel is showing up in the webpage's address, which usually happens when the 'bootstrap.js' file is missing, but I have included it. Can anyone help me troubleshoo ...

The mistake occurs when attempting to access a class property generated by a class constructor, resulting in a type error due to reading properties of

I'm having trouble building an Express API in TypeScript using Node.js. I am new to Express and I have been learning Node, JavaScript, and TypeScript since 2022, so I apologize if the question is not too complex. The issue I'm facing is trying to ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...

Is it possible to reuse a variable within a single HTML tag when using Angular 2?

I encountered a strange issue with Angular 2 that may be a bug. I noticed that I couldn't print the same variable in a template twice within the same HTML tag. When I tried to use the following code, it resulted in error messages. <div class=" ...

Troubleshooting a 404 error for an existing object: What to do?

I encounter a 404 'Not Found' error when attempting to edit a mark through my form. I am puzzled by the source of this error because in order to access this form, I require the brand ID (which can be found in the URL). Upon accessing my modifica ...

Encountered an issue while attempting to send a POST request using AngularJS $

I am facing an issue with accessing the POST method from my server. Whenever I log the response, it always returns status=0. Can anyone help me out or provide some advice? Note: I have tested the method in Postman and it works fine. Below is the code snip ...

Mandatory selection of jQuery extension

Currently, I am developing a custom jQuery plugin with the following code structure: (function($) { $.fn.foo = function(options) { var opt = $.extend({}, $.fn.foo.defaults, options); return this.each(function() { //code i ...

Sending arguments from an NPM script to a NodeJS script

In my main script (publish-all.js), I am trying to call the npm publish script of an Angular project. This Angular project also has a sub-script (publish.js) that performs various tasks (creating folders, copying files, moving folders...) after running ng ...

Incorporate a JavaScript solution for generating a dropdown menu, rather than relying on

I have been exploring a code snippet that dynamically creates and deletes text boxes using JavaScript. Here is the link to the code in action: http://jsfiddle.net/JpYGg/8/ My goal now is to modify this functionality to generate a set of three drop-down li ...

Encountered an issue while importing React with webpack: Unable to resolve module 'react'

I keep encountering an issue Error: Cannot resolve module 'react' (and react-dom) while using webpack. This project setup seems to be the most challenging one I've faced, and I'm struggling to figure out why it's not functioning pr ...

Istanbul provides me with a thorough analysis, yet it always seems to conclude with an error

Currently, I am experimenting with a basic application (found in the Mocha tutorial code available at ) to troubleshoot why Istanbul is giving me trouble. The issue is that Istanbul successfully generates a coverage summary but then throws an error for unk ...

What is the best way to troubleshoot a $http asynchronous request?

Is there a way to pause the program execution in AngularJS $http call after receiving a successful response? I've attempted to set a breakpoint at that point, but it does not halt the execution. I've also tried using the debugger directive, but ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

Paste the formatted text from clipboard into the body of a react mailto link

I have a requirement for users to easily send a table via email by copying and pasting it into the subject line. You can view a live demo of this feature on CodeSandbox: copy and paste rich text Below is the function that allows users to copy and paste ri ...

Struggling to add information to a database table with PHP

Check out the code snippet below: Here is the HTML5 code block: <div class="col-md-8 blogger-right-container"> <form action="blogger_account.php" method="post" role="form" enctype="multipart/form-data"> < ...