skip to content

JavaScript: Confirming user actions

An online application can never match the features of a desktop appliction, and as a rule, you shouldn't rely on scripting languages that aren't always available. Having said that, the use of some JavaScript can improve your user interface, and the user experience in general.

Protecting delete links with confirm

Suppose you have a 'back office' interface for a website that presents a list of 'products', with the option of editing or deleting each one. Your product list may then look something like the following:

IdProduct
1 Red Sprocket Delete
2 Blue Sprocket Delete
4 ... ...

When you click on one of the 'Delete' links in this example, you will be prompted to 'confirm' your action. This is a way of ensuring that items are not accidentally deleted, or the wrong item deleted by mistake.

For the security-conscious, forms of this type, particularly those that use GET variables to trigger events, are very susceptible to Cross-site request forgery (CSRF) attacks, which are very difficult to protect against. More on that later.

The syntax to add the 'confirmation prompt' is surprisingly simple:

<a href="..." onclick="return confirm('Are you sure?');">Delete</a> Some browsers will present the options as OK/Cancel and others as Yes/No. You can't change the buttons, the title or the format of the dialog box, so it's best to just pose a question for which both sets of options make sense.

In less technical terms: when the link is clicked, the confirm box is presented. If you click on Yes (or OK) then a value of true is returned and the href link is triggered. If you click on No (or Cancel) then a value of false is returned, which cancels the href action, meaning that the browser does not follow the link.

If JavaScript is disabled, the link will always be followed, and no confirmation dialogue will appear.

You can take advantage of this behaviour by having one action that applies in a JavaScript-enabled browser, and a default option for other browsers and agents, for example:

<a href="someimage.gif" onclick="window.open('someimage.gif'); return false;">show image</a>

For non-JavaScript browsers, this is a simple link to an image. For JavaScript-enabled browsers, however, the image will be displayed in a new pop-up window and the default link action cancelled. This is another example of ways you can use, but not rely on, JavaScript in your web applications.

In cases where you really want the user to be sure of their actions, you can add a second confirmation prompt requiring the user to twice confirm the action:

<a href="..." onclick="return confirm('Are you sure?') && confirm('Are you really sure?');">Delete</a>

If you're displaying data using PHP, then you will need to escape any quotes present in the confirmation prompt:

... onclick="return confirm('Delete this item: <?PHP echo addslashes($itemname) ?>?');" ...

References

< JavaScript

Post your comment or question
top