I'm starting in PHP O.O and I'm having a hard time calling functions that are in the class via HTML buttons.
In fact, it is not in calling but in setting the values that are in the function. Example:
<?php
Class Conta{
public $saldo;
public function __construct(){
$this->saldo = 50;
}
public function getSaldo(){
return $this->saldo;
}
public function setAdd(){
$this->saldo = $this->saldo - 10;
}
}
$c = new Conta();
$c->getSaldo();
$c->setAdd();
$c->getSaldo();
?>
Doing so, the program works exactly as I want, shows the starting balance, then changes the balance and shows the current value. Every time I invoke the getAdd () method it changes the value of the Balance.
However, I would like to do this through an HTML interface, for example using buttons:
<button onclick="saldo()">Saldo</button>
<button onclick="add()">Add</button>
I created two functions, one calling the file balance.php and the other calling add.php with the help of AJAX:
function saldo(){
var xhttp
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
document.getElementById("exibir").innerHTML = this.responseText;
}
};
xhttp.open("GET", "saldo.php?", true);
xhttp.send();
}
function add(){
var xhttp
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
document.getElementById("exibir").innerHTML = this.responseText;
}
};
xhttp.open("GET", "add.php?", true);
xhttp.send();
}
In the files of my.php and add.php I am just invoking the method. Ex.:
<?php
require_once "class.php";
$c->getSaldo();
?>
As the AJAX attempt had failed, I also tried forcing the conversation between JavaScript and PHP, like this:
function saldo(){
s = "<?php {$c->getSaldo();} ?>";
document.getElementById("exibir").innerHTML = s;
}
function add(){
s = "<?php {$c->setAdd();} ?>";
document.getElementById("exibir").innerHTML = s;
}
Both by AJAX and that way up there, you're not changing the BALANCE value. If I press the BALANCE button it shows me the initial value. If I press the ADD button it performs the function, but if I click the BALANCE button it remains the same.
NOTE: In the original program I created 4 files: INDEX.PHP, SALDO.PHP, ADD.PHP and CLASS.PHP, to separate the code. And the goal is not to use GET or POST methods, but to update without loading the page, as AJAX does ...
Could anyone help me with this question of running functions of a class with PHP O.O solving this problem that I quoted? Thank you.