Dynamically execute model class method from an ajax request to the controller

Asked

Viewed 1,833 times

4

I am creating a feature in my system for dynamic component reloading, so that queries are executed that are allocated in model layer classes, through AJAX requests. However, since I use the MVC standard from the Codeigniter framework, any request or execution must start from a control class, so I cannot run the queries directly through the model class where it is.

Would anyone know me a tool or technique that would facilitate my work? Being possible to execute the queries that are in the model in a safe way directly from the AJAX request, without passing in the controller? Or if not, is there any tool or function that would allow me to dynamically execute the model class methods from a controller to this function?

Just for the purpose of testing, I started to develop a method in a specific controller to dynamically execute the class and the method requested by parameter via request (http or ajax), but this function will be very difficult to use in production environment, since I have to define parameters and treat them according to the type when concatenating into the string, and worse, how they would be passed via url:

public function requestJson($classe, $metodo, $parametros = array()) {

echo "Executando o método <i>{$metodo}</i> a classe <i>{$classe}</i>:<br>";

$str = '$class = new ' . $classe . '();'
                . '$class->' . $metodo . '();';

        return eval($str);
}
  • 2

    The idea of MVC is for all requests to pass through a controller. Codeigniter already does a lot of magic by mapping controllers with URL routes. The right thing to do is to make model calls in your controller, or simply abandon MVC.

2 answers

1

The simplest is to call directly the model method

public function requestJson($classe, $metodo, $parametros = array()) {


$var =  "Executando o método <i>{$metodo}</i> a classe <i>{$classe}</i>:<br>";

    return json_encode($this->nome_do_model->requestJson($classe, $metodo, $parametros));
}

And in Model put the text return

public function requestJson($classe, $metodo, $parametros){
//executa os metodos e retorna para o controller
return "Executando o método <i>{$metodo}</i> a classe <i>{$classe}</i>:<br>";

}

1

What I usually do when I make an Ajax request is to call the controller, the controller requests the data, so I play it in a view or in a json to return the data to the ajax request.

html example:

<a href="#" id="exemploAjax">Link Ajax</a>
<div id="respostaAjax"></div>

example of js:

$('a#exemploAjax').click(function(e) {
    e.preventDefault();

    $.ajax({
        url: 'meu_controller/meu_metodo',
        type: 'POST',
        success: function(resp)  {

            var resp = $.parseJSON(resp);

            if (resp.success === true) {
                $('#respostaAjax').html(resp.msg);
            }
            else {
                alert(resp.msg);
            }
        }
    });
});

example of the controller:

class Meu_controller extends MY_Controller {

    public function meu_metodo()
    {
        $this->load->model('meu_model_m');
        $dados['items'] = $this->meu_model_m->get_items();

        $this->load->view('minha_view', $dados);
    }

}

model example:

class Meu_model_m extends MY_Model {

    public function get_items()
    {
        $query = $this->db
            ->select('nome')
            ->get('tabela_items');

        if ($query->num_rows() > 0) {
            return $query->result();
        }

        return array();
    }

}

example of the view:

<h1>Exemplo Ajax - Lista Items</h1>
<?php
echo '<ul>';
foreach ($items as $item) {
    echo '<li>';
    echo $item->nome;
    echo '</li>';
}
echo '</ul>';
?>
  • Marcelo, this method you demonstrated is necessary some framework not ?

  • Yes, Codeigniter that was in relation to his question!

Browser other questions tagged

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