Form confirmation on submit

tomaytotomato picture tomaytotomato · Feb 1, 2012 · Viewed 9k times · Source

I want to have a confirmation from the user before they submit a form. This will prevent accidental POSTing of the form, that may be incomplete or incorrect.

Here is my form element:

<form action="manager.php?method=update&id=<?php echo $user->id;?>" onsubmit="return confirm_update();"  method="POST" id="user_update"> 

This calls my function confirm_update()

function confirm_update()
{
  if(confirm("Do you wish to update details?"))
  {
    return 0;
  }
  else
  {
    return 1;
  }
}

The problem with the script is that it does not prevent the form from POSTing if the user clicks Cancel in the JavaScript prompt.

How do I correct this so that the user does not accidently submit their form?

Here is a full description of the feature I am trying to implement:

Use Case - "Update Details"

  • User goes to update page
  • User enters details in form fields
  • User hits submit button
  • Confirmation message appears
  • If "Ok" button selected proceed to submit form
  • Else cancel action and stay on current page

Answer

Rohan Prabhu picture Rohan Prabhu · Feb 1, 2012

Instead of returning 0 and 1, return true and false. You can actually shorten the function to:

function confirm_update() {
    return confirm("Are you sure you want to submit?");
}