Ajax running Controller (MVC, PHP)

5

I've just started to study mvc, and I have a question. How to make my ajax execute certain method of my controller. Note: I am not using any framework, here is the code below.

View

<div class="form-cadastro">

    <input type="text" class="form-control" id="nome" placeholder="Nome" required autofocus>
    <input type="text" class="form-control" id="nome_usuario" placeholder="Nome de Usuário (Apelido)" onkeydown="Mask(this,user);" onkeypress="Mask(this,user);" onkeyup="Mask(this,user);" maxlength="20">
    <input type="text" class="form-control" id="nascimento" placeholder="Data de Nascimento" onkeydown="Mask(this,DataM);" onkeypress="Mask(this,DataM);" onkeyup="Mask(this,DataM);" maxlength="10">
    <input type="email" class="form-control" id="email" placeholder="Email" required autofocus>
    <input type="password" class="form-control" id="senha" placeholder="Senha" required>

    <div class="termos text-center">
        <a data-toggle="modal" data-target="#modal-termos">Termos de Uso</a>
    </div>

    <div class="btn btn-lg btn-primary" id="btn-cadastro">Aceitar os termos de uso e Cadastrar</div>

  </div>

js

$.ajax({
        type: 'post',
        data:{
            nome: nome,
            username: username,
            nascimento: nascimento,
            email: email,
            senha: senha
        },
        dataType: 'json',
        url: 'controller/cadastro/index.php',
        success: function(msg){

            if(msg.erro == 0){

                window.location.href = "dashboard";

            }else{

                swal('Não foi possível cadastrar');
                fnLoading(false);
                return;

            }

        }

    })

controller

class cadastro{

    public function cadastrar(){

        $player = new Player();

        $player->nome       = mysql_escape_string($_POST['nome']);
        $player->username   = mysql_escape_string($_POST['username']);
        $player->nascimento = mysql_escape_string($_POST['nascimento']);
        $player->email      = mysql_escape_string($_POST['email']);
        $player->senha      = mysql_escape_string($_POST['senha']);

        $player->inserir();

    }

}
    
asked by anonymous 06.05.2017 / 14:37

1 answer

0

The error will not be in ajax ?

You have:

url: 'controller/cadastro/index.php'

You should stay:

url: '_caminho_/cadastro/cadastrar'

Since the link to call a controller follows the following pattern:

Caminho/Controller/Method/

Being:

  • Caminho : Corresponds to the path to the controller;
  • Controller : Driver name;
  • Method : Method to use inside the controller.

But if you want to work with MVC, I recommend using a framework, such as Laravel or CodeIgniter .

    
11.05.2017 / 11:06