How to echo on same html page after form submit?

31,995

Solution 1

I guess you can use a combination of <iframe> and javascript to get the results.

<form method="post" action="submit.php" target="myIframe" >
    <input type="submit" name="1" value="YES" />
    <input type="submit" name="1" value="NO" />
</form>

<iframe name="myIframe">
</iframe>

Solution 2

You can't do it on the same page - at least not without asynchronous client-server communication techniques such as AJAX. Otherwise, you can use the following:

<form action="<?php echo $_SERVER['PHP_SELF']; ? method=....>"

as your form opening tag, then put the PHP processing code at the top of the document, like this:

<?php
  if(isset($_POST['form_field_name'])){
       //process your data here
?>

HTML in case of Form filled in goes here

<?php
}else{
?>

HTML in case of Form not filled in goes here

<?php
  }
?>

HTML in any case goes here

This way you can change the layout of your page depending on whether the form was filled in or not. the $_SERVER['PHP_SELF'] contains the reference to the currently requested page, and therefore is always set to the correct page even if it is renamed. This can save you time when bug-tracking.

Solution 3

<?php

if(isset($_POST['1'])){
    echo ($_POST['1'] == 'YES') ? 'Good!!!' : 'Try Again!';
}

?>

<!-- your HTML goes here -->

You can combine HTML and PHP on the same page.

Share:
31,995
Tasos
Author by

Tasos

Updated on November 24, 2020

Comments

  • Tasos
    Tasos over 3 years

    When the form is submitted, my page is redirected to the PHP and the echo is displayed. How can I display the echo without being redirected to the PHP page? So the echo should be displayed in the html page (where the html form is located).

    <form method="post" action="../form.php">
    <input type="submit" name="1" value="YES" />
    <input type="submit" name="1" value="NO" />
    </form>
    

    -

    <?php 
    $answer = $_POST['1'];  
    if ($answer == "YES") {          
        echo 'Good!!!';      
    }
    else {
        echo 'Try Again!';
    } 
    ?>