php – Show message after submit-ThrowExceptions

Exception or error:

How can I display an alert after a user clicks a submit button in a form?

I want the alert to show when the page has loaded after the submit button has been clicked.

Is there any way to do this?

EDIT:

I need the message to be HTML text that is displayed on the page–not a javascript alert.

How to solve:

pagewithform.php

<html>
  <head>
  ...
  </head>
  <body>
    ...
    <form action="myformsubmit.php" method="POST">
      <label>Name: <input type="text" name="name" /><label>
      <input type="Submit" value="Submit" />
    </form>
    ...
  </body>
</html>

myformsubmit.php

<html>
  <head>
  ....
  </head>
  <body>
    <?php if (count($_POST)>0) echo '<div id="form-submit-alert">Form Submitted!</div>'; ?>
    ...
  </body>
</html>

EDITED Fits new critieria of OP on last edit.

EDITv2 Try it at home!

<html>
  <head>
    <title>Notify on Submit</title>
  </head>
  <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
      <label>Name: <input type="text" name="name" /></label>
      <input type="submit" value="Submit" />
    </form>
    <?php if (count($_POST)>0) echo "Form Submitted!"; ?>
  </body>
</html>

Try that on for size.

Answer:

Since you’re submitting back to the same page, a cleaner and more modern way of doing this would be to use JQuery to submit the form using AJAX. You can then specify a callback method that will update a container on the page to reflect the change in state:

$('#myForm').submit(function() {
   $('#myResultDiv').text("Form submitted");
   return false;
});


... 

<div id="myResultDiv"></div>

This prevents the unnecessary reloading of the page, making your web application snappier and more responsive.

This also has the added benefit of keeping your HTML and JavaScript (content and behavior) separate, for which your web designers will thank you for.

This would work with just about any server-side platform, including but not limited to PHP.

Answer:

<?php

echo "<html>
<head>
</head>";

if($_POST['submit']){
     echo 'The form was submitted!";
} else {
    echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST"><input type="submit" name="submit" value="Submit">';
}

echo "</html>";

?>

Answer:

Since you’re submitting back to the same page, a cleaner and more modern way of doing this would be to use JQuery to submit the form using AJAX. You can then specify a callback method that will update a container on the page to reflect the change in state:

Leave a Reply

Your email address will not be published. Required fields are marked *