Calling functions/procedure via buttons using Object-Oriented PHP

Asked

Viewed 1,359 times

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;

  • Updated buddy, take a look again please.

1 answer

2


This conversation between javascript and PHP, can only be done with ajax, or at the beginning of the page with PHP above 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 make it 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 receive the methods by POST, there are libraries that streamline this process, at hand it is like this

    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 didn’t test the code but that’s basically it

  • Got it Felipe, I’ll give a studied in your code and test. Could you make this same code using "pure" AJAX, without Jquery? Another thing I don’t understand is, when I was doing as in the first example I posted, calling the methods normally, everything worked out good and when I just tried calling them by button it was necessary to add so much code so after the object was instantiated?

  • I don’t handle pure javascript once kk, so it would be hard... In fact it is necessary yes, at least if you intend to call them without updating the page, orientation to objects with php is a bit complex with applications Realtime, other server languages do it better, in case calling the method by onclick would be impractical, so javascript does not generate php and also this type of procedure is very insecure

  • I got rsrsr. Could you tell me another method more coherent than onclick for this purpose? Thanks for the feedback bro.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.