2
I’m starting in PHP O.O and I’m having difficulty calling the functions that are in the class through 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 initial 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 for an HTML interface, for example using buttons:
<button onclick="saldo()">Saldo</button>
<button onclick="add()">Add</button>
I created two functions, one calling the.php balance file and the other calling add.php using 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.php balance and add.php files I’m just invoking the method. Ex.:
<?php
require_once "class.php";
$c->getSaldo();
?>
As the attempt by AJAX 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 this way from up there, it is not changing the value of the BALANCE. 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 someone help me in this matter of running functions from a class with PHP O.O solving this problem I mentioned? Thank you.
The way it is is not going to work. Post the code of how you tried via ajax;
– Rodrigo Jarouche
Updated buddy, take a look again please.
– Eduardo Pereira