I'm basically starting studies with PHP and what I'm trying to do is simple. I would like to display the result of a calculation on the same page.
The structure of my project follows:
Mycodes:
index.php:
<?phpinclude"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 get the values in the index.php with the calc.php file. And in the file calc.php I pass the values to the calc.inc.php so that in this the calculations are performed and the final value for calc.php is returned. The problem is that in the method > is redirected to the calc.php page and the result is displayed on this other page, being that I would like it to appear on the same index.php page.
I tried to do something with Header ("Location: index.php") but this causes the page to refresh, so it did not work. Is it possible to do what I want? I accept different types of solutions!