Send form data by Ajax in MVC project

1

To begin with, I'll give you a little example of the system for you, my directory structure is as follows:

>leganto(raiz)
---> controller
-------> ControllerGlobal.php
-------> OutrosControllesDeObjetos

---> model
-------> ModelDeObjetos

---> view
-------> objeto
-----------> CRUDdeCadaObjeto

---> libs
---> css
---> imgs
---> js

---> ajax
-------> arquivosDeRequisicaoAjax

---> index.php

Only the Controller and Model layers are oriented and the View is structured.

I use url friendly where I have 1 to 3 parameters in url, I can have url as follows:

  • site / act
  • site / object / act
  • site / object / act / id

In short, act would be my method, object my class and id is used for when I want to display a bank record. That is, in the registration screen I will have the link:

site/account/create //vai instânciar o controller account e executar seu método create

The whole application flow starts in index.php , in it I instantiate my ControllerGlobal and call its request method that takes objeto and ato url and instance controller objeto executing método referring to ato taken by url.

Let's go to the problem, I have the register view that is called whenever the url is site/account/create , the url makes the CrontrollerGlobal execute this code (which is the create method of my account controller):

private function create()
{
    $title = "Registre-se no Leganto"; // titulo da página
    $icon = "plus"; // icone da página

    // quando o formulário de cadastro for enviado, com token de proteção
    if(isset($_POST['userinsertrequest']) and $_POST['userinsertrequest'] == $_SESSION['token'])
    {
        try
        {
            $user = array(); // cria array com dados
            foreach ($_POST as $key => $value)
            {
                $user[$key] = addslashes(htmlentities($value));
            }
            // chama model que faz o insert
            $insert = $this->model->prepareNewUser($user);
            if($insert)
            {
                // se registrou volta pra tela de login
                header("Location:{$_SESSION['self']}");
            }
            else
            {   // se não fala que houve um erro desconhecido
                $error = "Houve um error ao gravar o usuário.";
            }
        }
        catch(Exception $ex)
        {   // pega erro de validação de dados do model
            $error = $ex->getMessage();
        }
    }

    // inclui meu view de cadastro
    include 'view/account/user-create.php';
}

I want to insert the data of my formulário of register in the $_POST and execute this function above to make the registration, this with the AJAX not to have the loss of the data entered. I tried the following:

$(function()
{
    // quando meu formulário for submetido
    $("form[name = fm-register-user]").submit(function()
    {
        alert("ENVIOU"); // alerta funcionou
        $.ajax({
            type: "POST",
            url: "account/create", // tenta requisitar a função de criar
            data: { // pego meus dados incluindo o token
                name:               $("input[name = name]").val(),
                email :             $("input[name = email]").val(),
                date :              $("input[name = date]").val(),
                username :          $("input[name = username]").val(),
                password :          $("input[name = password]").val(),
                confirmpassword :   $("input[name = confirmpassword]").val(),
                ocupation :         $("input[name = ocupation]").val(),
                history :           $("input[name = history]").val(),
                userinsertrequest : $("input[name = userinsertrequest]").val()
            } ,
            success: function(retorno) {
                alert(retorno); // dou alerta na minha mensagem de retorno

            }
        });
    });
});

On purpose I left an error in my insert in the database to test and see if the error was displayed in the alert, but when I submit the form only the alert for "ENVIOU" is displayed.

My view looks like this:

<?php
/**
 * Created by PhpStorm.
 * User: Leonardo Vilarinho
 * Date: 10/03/2016
 * Time: 14:51
*/

$printError = (isset($error))
    ? "<div class='text-danger text-center'><strong>{$error}</strong></div>"
    : "";

$_SESSION['token'] = md5(time());
$_SESSION['title'] = (!empty($title)) ? $title : "";
/*
  "usuarios",
                    array("username", "email", "password",
                        "image", "name", "date",
                        "ocupation", "history", "active", "token"),
 * */
?>
    <section class="row">

        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-success">
                <div class="panel-heading">
                    <h3 class="panel-title">
                        <i class="fa fa-<?php echo (!empty($icon)) ? $icon : ""; ?>"></i>
                        <?php echo (!empty($title)) ? $title : ""; ?>
                    </h3>
                </div>
                <?php echo $printError; ?>

                <form method="post" name="fm-register-user">
                    <div class="panel-body">
                        <table class="table form-group-sm">
                            <tr class="text-center text-muted">
                                <td colspan="10">
                                    <input name="image" type="file" accept=".jpg, .png">
                                    <img src="<?php echo $_SESSION['self'] ?>imgs/cover.jpg" style="width: 100px;" class="img-circle profile">
                                    <p>Foto do Perfil</p>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="1">Nome Completo:</td>
                                <td colspan="9">
                                    <input name="name" maxlength="255" required  placeholder="Nome Completo" type="text" class="form-control"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="1">Email:</td>
                                <td colspan="7">
                                    <input name="email" maxlength="200" required  placeholder="Email" type="email" class="form-control email validar-email"/>
                                </td>
                                <td colspan="1">Nascimento:</td>
                                <td colspan="1">
                                    <input name="date" required type="date" class="form-control"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="1">Usuário:</td>
                                <td colspan="5">
                                    <input name="username" maxlength="20" required  placeholder="Usuário" type="text" class="form-control"/>
                                </td>
                                <td colspan="4" class="text-muted">
                                    <p>(Sem espaços e acentos.)</p>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="1">
                                    Senha:
                                </td>
                                <td colspan="7">
                                    <input name="password" maxlength="15" id="senha" required placeholder="Senha" type="password" class="form-control" />
                                </td>
                                <td colspan="1" class="confirm">
                                    Senha:
                                </td>
                                <td colspan="1" class="confirm">
                                    <input name="comfirmpassword" maxlength="15" id="senha2" required placeholder="Confirmar Senha" type="password" class="form-control" />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="10">
                                    <div class="barprogress text-center" style="color: white; border: 1px solid #b4b5b2;">
                                        <div>.</div>
                                    </div
                                </td>
                            </tr>
                            <tr>
                                <td colspan="1">Ocupação:</td>
                                <td colspan="9">
                                    <input name="ocupation" maxlength="255" required placeholder="Ocupação" type="text" class="form-control" />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="1">Sobre:</td>
                                <td colspan="9">
                                    <textarea placeholder="Conte-nos sua história..." maxlength="255" name="history" required class="form-control"></textarea>
                                    <div class="text-right count">
                                        <p>0 / 255</p>
                                    </div>

                                </td>
                            </tr>
                        </table>
                        <input name="userinsertrequest" value="<?php echo $_SESSION['token']; ?>" type="hidden" />

                    </div>
                    <div class="panel-footer text-center">
                        <a class="btn btn-danger" href="<?php echo $_SESSION['self']; ?>" >Cancelar</a>
                        <input value="Criar" type="submit" class="btn btn-success" />
                    </div>
                </form>
            </div>
        </div>
    </section>

<?php
$_SESSION['scripts'] = "<script src='{$_SESSION['self']}libs/formzin.js'></script>";
$_SESSION['scripts'] .= "<script src='{$_SESSION['self']}js/verify-password.js'></script>";
$_SESSION['scripts'] .= "<script src='{$_SESSION['self']}js/profile-inputs.js'></script>";
$_SESSION['scripts'] .= "<script src='{$_SESSION['self']}ajax/register-user.js'></script>";

In theory I think ajax is correct but it is not working. I do not know if it is because the model layer errors are Exceptions , because I do not know if Ajax captures Exceptions as a return.

    
asked by anonymous 07.04.2016 / 20:24

1 answer

1
  

Keep in mind that MVC is not a technology, it's just a way to get things done, your problem looks like the route.

So Ajax is nothing more than a background request running on a Javascript API, if you use the url like this in brower account/create and it works then it should work in ajax, in short I suspect the url where it is the call ajax, for example http://localhost/projeto/exemplo/ when executing ajax like this:

$.ajax({
    type: "POST",
    url: "account/create",

You will interpret http://localhost/projeto/exemplo/account/create , but I understand that in fact the desired one would be this http://localhost/projeto/account/create , what you can try then is this:

$.ajax({
    type: "POST",
    url: "../account/create",

A tip, always add error to $.ajax to detect problems, for example:

$.ajax({
    type: "POST",
    url: "account/create",
    data: {
        name:               $("input[name = name]").val(),
        email :             $("input[name = email]").val(),
        date :              $("input[name = date]").val(),
        username :          $("input[name = username]").val(),
        password :          $("input[name = password]").val(),
        confirmpassword :   $("input[name = confirmpassword]").val(),
        ocupation :         $("input[name = ocupation]").val(),
        history :           $("input[name = history]").val(),
        userinsertrequest : $("input[name = userinsertrequest]").val()
    } ,
    success: function(retorno) {
        alert(retorno); // dou alerta na minha mensagem de retorno

    } ,
    error: function(xhr, status, error) {
        console.log(status, error);//Captura o erro e envia ao console
    }
});

A PHP tip is that when using location: it is preferable not to send anything to output, so do this:

if($insert)
{
    // se registrou volta pra tela de login
    header("Location:{$_SESSION['self']}");
    exit;
}

Just do not use exit; you may need to do something else "after" after location .

    
07.04.2016 / 20:36