0
I am basically starting studies with PHP and what I am trying to do is simple. I would like to display the result of a calculation on the same page.
Follow the structure of my project:
My codes:
index php.:
<?php include "header.php"; ?>
<?php include "footer.php"; ?>
header.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="calc.php" method="POST">
<input type="text" name="num1">
<input type="text" name="num2">
<select name="cal" id="">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
</select>
<button type="submit">Calculate</button>
</form>
Calc.php:
<?php
include 'includes/calc.inc.php';
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$cal = $_POST['cal'];
$calculator = new Calc($num1, $num2, $cal);
echo $calculator->setCalc(); //gostaria de mostrar na mesma página
Calc.inc.php:
<?php
class Calc{
public $num1;
public $num2;
public $cal;
public function __construct($num1, $num2, $cal){
$this->num1 = $num1;
$this->num2 = $num2;
$this->cal = $cal;
}
public function setCalc(){
switch($this->cal){
case 'add':
$result = $this->num1 + $this->num2;
break;
case 'sub':
$result = $this->num1 - $this->num2;
break;
case 'mul':
$result = $this->num1 * $this->num2;
break;
default:
$result = "Error";
break;
}
return $result;
}
}
I recover the values in index php. with the file Calc.php. And in the archive Calc.php I pass the values to the Calc.inc.php so that the calculations are performed and the final value is returned to the Calc.php. The problem is that in method is redirected to the page Calc.php and the result is displayed on this other page, I’d like it to appear on the same page as index.php.
I tried to do something with Header("Location: index.php") but this causes the page to update, so it didn’t solve. Is it possible to do what I want? I accept different types of solutions!
You can check if the
POST
, if it isPOST
just display the result.– gato