Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

php

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";
?>
like image 221
Kai Avatar asked Nov 29 '25 20:11

Kai


2 Answers

<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>
like image 78
keyboardSmasher Avatar answered Dec 02 '25 10:12

keyboardSmasher


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.

like image 45
Lior Avatar answered Dec 02 '25 09:12

Lior