Call functions / procedure via buttons using Object Oriented PHP

1

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.

    
asked by anonymous 18.02.2017 / 03:19

1 answer

0

This conversation between javascript and PHP, can only be done with ajax, or at the top of the page with PHP above the javascript, to get better I will add 2 more inputs

    <button class="getSaldo">Saldo</button>

    <input type="text" id="saldo">

    <button class="setSaldo">Add</button>

    <input type="text" id="add">

I used J-query to get easier

    $(".getSaldo").on("click", function(){


        $.ajax({
                    type : "POST",
                    url  : "tuaClasse.php",
                    data: {metodo: 'getSaldo'},
                    dataType: "json",
                    success :  function(response){

                        if (response.codigo == 1) {
                            alert(response.mensagem)
                        }
                        if (response.codigo == 0) {

                            $("#saldo").val(response.valor);

                        }

                    }

                })

    })

    $(".setSaldo").on("click", function(){

        var saldo = $("#add").val();

        $.ajax({
                    type : "POST",
                    url  : "tuaClasse.php",
                    data: {metodo: 'setAdd', valor: saldo},
                    dataType: "json",
                    success :  function(response){

                        if (response.codigo == 1) {
                            alert(response.mensagem)
                        }
                        if (response.codigo == 0) {

                            $("#add").val(response.valor);

                        }

                    }

                })

    })

In PHP you get the methods through POST, there are libraries that streamline this process,

    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();

    $metodo = (isset($_POST['metodo'])) ? $_POST['metodo'] : '';
    $saldo = (isset($_POST['valor'])) ? $_POST['valor'] : '';

    if($metodo == "getSaldo"){

        $valor = $c->getSaldo();

        $retorno = array('codigo' => 0,'valor' => $valor);

        echo json_encode($retorno);
        exit();

    }

    if($metodo == "setSaldo"){

        $valor = $c->setAdd($saldo); //por causa do método contrutor isso não ira funcionar, mas ele iria adicionar -10 a um valor que você enviasse

        $retorno = array('codigo' => 0,'valor' => $saldo);

        echo json_encode($retorno);
        exit();

    }

    else{
        $retorno = array('codigo' => 1,'mensagem' => "Erro desconhecido");

        echo json_encode($retorno);
        exit();
    }

NOTE: I have not tested the code but this is basically

    
18.02.2017 / 04:06