How do you pass data to a php class via ajax when this is another instance class?

Asked

Viewed 1,406 times

-1

Hello guys I hope you can help me, I’ve been having this problem for a long time

I pass my data via Ajax to my class but in the URL do not know how to reach it in a way other than error

I tried it this way

$.ajax({
     type:'post',
     url:'Classes/Usuario.class.php',
     ajax:'1',
     data:{id:1},
     success: function (data){
          alert(data)
     }
});

Well, remarks if you help me answer.

It is Obviou that will give error kkkk, as said my other instance User class, extends another so I can not pass my values like this.

Another thing that may help, my classes are called automatically by the magic __autoload() method. I believe that in this way there is a different way to write the URL.

Good people, please do not indicate another post, if you do not understand tell us in the comments that are with you until we can solve this problem !

Thank you for helping me ! until..

As requested I am just below comes the code of the file Usuario.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Pedro
 * Date: 19/01/2016
 * Time: 00:43
 */

class Usuario extends BancoPizza
{
    public $Tabela = 'pizzaria';
    public $Campos = array(
        'nome_pizzaria',
        'usuario_pizzaria',
        'senha_pizzaria',
        'rua_pizzaria',
        'numero_pizzaria',
        'bairro_pizzaria',
        'cidade_pizzaria',
        'uf_pizzaria',
        'status_pizzaria'
    );



    /**
     * @param $dados -> Campos da tabela
     * @param $Campos -> A classe ja tem os campos da tabela
     */


    public function verUm($where=null){
        return parent::verUm($this->Tabela, $where);
    }

    public function verTodos($where=null, $ordem=null)
    {
        return parent::verTodos($this->Tabela, $where, $ordem);
    }

    public function excluir($where)
    {
        //Aqui eu queria pegar a Id do item clicado e através do ajax passar essa id, porem preciso saber como especificar o método que esse meu valor vai, correto ?
        return $_POST['id'];
        return parent::excluir($this->Tabela, $where);
    }

    public function editar($campoTabela, $valor, $id)
    {
        parent::editar($this->Tabela, $campoTabela, $valor, $id);
    }
}
  • The class does not stop being a file so just take the post and pass the values to the object

  • post your User code.class.php. The above code should go to some method in the correct User class? Which one?

  • @Thomaslima - dear you said a very impractical thing, specify the method my values go to, to top updated the code. It became clearer to help me ?

  • @Pedrosoares apparently your only problem is lack of information for which method you want to send your data. Are you using MVC? Ideally you send your data to a control class, it will be responsible for instantiating your user class and calling the corresponding method.

  • Do not send the post directly to the class file! Send it to another php page that includes the necessary classes, instates them and does all the necessary process.

  • @Thomaslima I think I’m getting the idea, can you explain me how to call the method from the URL ?

  • @Pedroerick - I’ll try this, but Thomas is right, I need to call the method besides calling the class and instating it. but I don’t know how I do it.

Show 2 more comments

1 answer

1

Partner, assuming you’re not using MVC, I suggest something like this:

$("body").delegate(".btnAcao", function(e){
     e.preventDefault() //Retirando o comportamento padrão

/*
     *Você pode recuperar os valores do seu form utilizando o método .serializeArray()
     */
    var arrayDados = $("#id_do_form").serializeArray();
    arrayDados['funcao'] = 'excluir';


    $.ajax({
         type:'post',
         url:'Classes/usuario-controller.class.php',
         data: arrayDados,
         success: function (data){
              alert(data)
         }
    });

});

Rather than directly calling your User class, you send your data to another page that will be responsible for making that link between your view (View) and your User (Model) class. I called this new user-controller.php file.

Note that the values of my form were taken with the .serializeArray()

php user-controller.

<?php

/**
 * adiciona todos os seus includes que você precisa...
 * 
 * Nesse momento você pode recuperar os valores do seu form normalmente.
 * Aqui você também poderá tratar suas variáveis, limpando-as e se certificando de 
 * que os dados que foram inseridos estão corretos
 */
$id = filter_input(INPUT_POST, 'id');
$nome = filter_input(INPUT_POST, 'nome');
$email = filter_input(INPUT_POST, 'email');
$telefone = filter_input(INPUT_POST, 'telefone');

$metodo = filter_input(INPUT_POST, 'funcao');


//Instancia a classe que precisa
$usuario = new Usuario();

/**
 * A partir desse momento você poderá chamar o método que você deseja.
 * 
 * OBS: Lembrando que o seu retorno para o página anterior virá daqui...
 * 
 * Como exemplo, vamos excluir o registro informado:
 */

echo $usuario->$metodo($id);

//Se tudo ocorrer bem, o seu retorno será true.

The logic is this, just adapt to what you need.

I hope I’ve helped!

  • It is not possible to do this within my class I have functions, and do not know how to do for the right function receive the value passed by ajax.. any idea ?

  • @Pedrosoares the correct thing is for the user-controller.php file to receive the data, create the User instance and manipulate its functions. You can create another parameter in the ajax called function for example, there you pass the name of the method you want to call. See edited response. You can even do this directly in the User class, but you will have to make this logic of receiving the data and instantiating the class outside the class definition, ie outside the { ... }

  • Yes, yes, that’s what I need. Finally, you can show me an example ?

Browser other questions tagged

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