Kai
Kai

Reputation: 51

How can I get the HTML form results in the same page of browser?

I am typing a simple codes in PHP and HTML. How can I display the result in same page of browser not in another window tab or page?

Following is the simple HTML formula code:

To add two numbers and display on the same page

<html>
<head>
    <title> Sum of two numbers </title>
<body>

    <form action="sum.php" method="POST">
    First Number:  <input type="Text" Name="Num1"><br>
    Second Number: <input type="Text" Name="Num2"><p>
    <input type="Submit" value="Calculate">
    </form>

</body>
</html>

and sum.php file is as follows.

<?php
// add First and Second Numbers
$sum = $_POST["Num1"] + $_POST["Num2"];
// their sum is diplayed as
echo "The sum of  First Number (".$_POST["Num1"].") and
Second Number  (".$_POST["Num2"].") is $sum";
?>

Upvotes: 3

Views: 11968

Answers (3)

el Dude
el Dude

Reputation: 5183

<html>
<head>
    <title> Sum of two numbers </title>
<body>
<?php 
if($_POST["Num1"]=='' And $_POST["Num2"]==''){
?>      
    <form action="sum.php" method="POST">
    First Number:  <input type="Text" Name="Num1"><br>
    Second Number: <input type="Text" Name="Num2"><p>
    <input type="Submit" value="Calculate">
    </form>
<?php }else{
// add First and Second Numbers
$sum = $_POST["Num1"] + $_POST["Num2"];
// their sum is diplayed as
echo "The sum of  First Number (".$_POST["Num1"].") and
Second Number  (".$_POST["Num2"].") is $sum";
} ?>
</body>
</html>

and sum.php file is as follows.

Upvotes: 1

keyboardSmasher
keyboardSmasher

Reputation: 2811

<html>
<head>
    <title> Sum of two numbers </title>
<body>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    First Number:  <input type="Text" Name="Num1"><br>
    Second Number: <input type="Text" Name="Num2"><p>
    <input type="Submit" value="Calculate">
    </form>

<?php
if (count($_POST) > 0 && isset($_POST["Num1"]) && isset($_POST["Num2"])){
    // add First and Second Numbers
    $sum = $_POST["Num1"] + $_POST["Num2"];
    // their sum is diplayed as
    echo "The sum of  First Number (".$_POST["Num1"].") and
    Second Number  (".$_POST["Num2"].") is $sum";
}
?>
</body>
</html>

Upvotes: 4

Lior
Lior

Reputation: 6051

You have to combine the PHP code and the HTML code in the same file.
Then you just set the forms action to the same page.

Upvotes: 2

Related Questions