Ajax does not reach the controller in cakephp

1

Hello, I have the following codes: Routes

Router::connect('/', array('controller' => 'pages', 'action' => 'home', 'home'));
Router::connect('/post', array('controller' => 'Posts', 'action' => 'display', 'Posts/index'));
Router::connect('/admin', array('controller' => 'users', 'action' => 'login', 'admin' => true));

/**
 * ...and connect the rest of 'Pages' controller's URLs.
 */
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

Js

    $(".btnFormNeed").on("click", function () {
    if ($.validador()) {
        var parametros = {
            "NeedClient": $(".txtClient").val(),
            "NeedNeed": $(".txtNeed").val(),
            "NeedObjective": $(".txtObjective").val()
        };
        $.ajax({
            data: parametros,
            url: '/',
            type: 'post',
            dataType: "json",
            success: function (response) {
                if(response==="si"){
                    //logica para avanzar a la siguiente vista de cake, la cual no se como se haced desde Jquery
                } else{
                    //sacar mensaje flash de cake desde jquery lo cual tampoco se. 
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("error");
            }
        });
    }

});

I'm supposed to insert the form data, the thing is that I do not know what I should change to get to the url, the view is home, I show them ps routes where the driver's route is of home, and not if there is something that I have to change to insert.

PagesController

public function home() {
    if ($this->request->is('post')) {

        if (!empty($this->request->data)) {
            $this->Flash->error(__("Emty"));
            $this->loadModel('Need');

            $this->Need->create();
            if ($this->Need->save($this->request->data)) {
                $this->Need->save(array(
                    'date' => date("Y/m/d")
                ));

                $this->set('doctor', "si");
            }
            $this->set('doctor', "no");
        } else {
            $this->set('doctor', "no");
        }
    } else {
        $this->set('doctor', "no");
    }
}

That is the controller, the thing is that you can not read the paramatros that you send by post method, to insert them in the database, in pure php you would read $_POST["NeedClient"]; $_POST["NeedNeed"]; $_POST["NeedObjective"]; but in cake I do not know how to do it.

Home - view

    <div id="divNeeds" class="row" hidden="true">
    <div class="container">
        <div class="row">
            <div class="col-5">
                <h1 id="h1NeedsTitle" class="lang" key="h1NeedsTitle">Descubrir necesidades</h1>
                <h4 class="lang" key="h4FNeedsFirstText">
                    El comienzo de una estratégia funcional es conoces nuestro <br>
                    objetivo y que necesidades queremos resolver, de esta forma <br>
                    nuestro equipo a través de un laboratorio enlaza un vínculo con <br>
                    la marca y da comienzo al plan estrategico.
                </h4>
            </div>
            <div class="col-1">
            </div>
            <div class="col-6">
                <?php
                echo $this->Form->create('Need', array('class' => '', 'id' => 'msform'));
                ?>
                <h1 class="lang" key="h1NeedForm">Aprovechemos el tiempo y comencemos</h1>
                <?php
                echo $this->Form->input('client', array('label' => array('text' => "¿Para que marca vamos a trabahar?",
                        'key' => 'lblClient', 'class' => 'lang'), 'placeholder' => 'Dinos el nombre de tu empresa',
                    'class' => 'validador txtClient lang', 'key' => 'txtClient'));
                echo $this->Form->input('need', array('label' => array('text' => "Escríbenos acerca de tu necesidad",
                        'key' => 'lblNeed', 'class' => 'lang'), 'placeholder' => 'Agradecemos nos detalles muy bien la necesidad, '
                    . 'es nuestro punto de partida para generar ideas quer fortalezcan la estrategia para resolverla.',
                    'rows' => '4', 'class' => 'validador txtNeed lang', 'key' => 'txtNeed', 'style' => 'resize: none;'));
                echo $this->Form->input('objective', array('label' => array('text' => "¿Cuál es el objetivo?",
                        'key' => 'lblObjective', 'class' => 'lang'), 'placeholder' => 'Que se quiere alcanzar con la'
                    . 'solución de la necesidad, ¿Adquirir usuario? ¿Mejorar ventas? ¿Posicionar la marca? ... entre otros.'
                    . ' Agradecemos nos detalles muy bien el objetivo.', 'rows' => '4',
                    'class' => 'validador txtObjective lang', 'key' => 'txtObjective', 'style' => 'resize: none;'));
                ?>
                <div class="container">
                    <div class="row">
                        <div class="col-6">
                            <label class="lang" key="lblAddNeed">Tienes otra necesidad </label>
                            <img src="https://image.flaticon.com/icons/png/512/37/37240.png" class="imgAddNeed"/>
                        </div>
                        <div class="col-6">
                            <?php
                            $options = array(
                                'class' => 'lang btnFormNeed',
                                'label' => 'Enviar y continuar',
                                'key' => 'btnFormNeed',
                                'type' => 'button'
                            );
                            echo $this->Form->end($options);
                            ?>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
    
asked by Andrés Vélez 28.04.2018 в 00:56
source

2 answers

0

In your function ajax you are saying that the request is of type GET , so your $this->request->data is empty, change the type to POST

$(".prueba").on("click", function () {
    console.log("hola");
    var parametros = {
        "doctorName": $(".doctorTitle").text(),
        "loActivo": "Si"
    };
    console.log("111");
    $.ajax({
        data: parametros,
        url: '/',
        type: 'POST', // Aquí le decimos que la petición es de tipo POST
        dataType: "json",
        beforeSend: function () {
            $("#resultado").html("Procesando, espere por favor...");
        },
        success: function (response) {
            // Tu lógica a seguir de acuerdo a la respuesta obtenida
            console.log("1"+response+"1");
            console.log("2"+respose.data.items.doctor+"2");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error");
        }
    });
});

And in the controller method, your data validation is upside down

public function home() {
    // Revisamos si la petición es POST
    if ($this->request->is('post')) {
        // Revisamos si la petición POST tiene datos
        if (!empty($this->request->data)) {
            $this->loadModel('Need');
            $this->Need->create();
            if ($this->Need->save($this->request->data)) {
                $this->Need->save(array(
                    'date' => date("Y/m/d")
                ));
            }

            $this->set('prueba', 'HOLAAA');
        }
    }
}
    
answered by 28.04.2018 в 01:04
0

little guide

1.- INSERT THE JQUERY LIBRARY

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>

2.- THE FORM

Have a view or HTML where you have a form. In the form it will be necessary to create an identifier for the select option in this case I have put:

<select id="select_categoria">
      <option value="1">categoria1</option>
      <option value="2">categoria2</option>
      <option value="3">categoria3</option>
    </select>

It will also be necessary to create a div or a p so that when the select option is returned with the subcategories they are painted in an html.

<div id="div_subcategorias_wrapper"></div>

3.- THE JQUERY FUNCTIONS The id that we have put to the select option of the categories is used so that jquery makes a bindeo to a certain action that we specify.

$("document").ready(
function() {

    $('#select_categoria').bind('click', function()
    {
        $.ajax({
               type: "GET",
               url: "/articulos/obtener_subcategorias/"+$(this).val(),
               beforeSend: function() {
                     $('#div_subcategorias_wrapper').html('<div class="rating-flash" id="cargando_div">Cargando  <img src="/img/ajax-loader_mini.gif"></div>');
                     },
               success: function(msg){
                   $('#div_subcategorias_wrapper').html(msg);
               }
             });
    });

}
);

4.- THE CONTROLLER OR THE PHP LOGIC

<?php
class ArticulosController extends AppController
{
    var $uses = array('Articulo','ArticuloCategoria','ArticuloSubcategoria');
    function index()
    {
        // lógica
    }

    function obtener_subcategorias($id)
    {
        $this->layout = 'ajax';
        // aquí la lógica que uséis para obtener datos de la <a href="https://www.pedroventura.com/tag/base-de-datos/" data-wpel-link="internal">base de datos</a>
        // y generar un array con todas las categorías
        // por lo normal y rápido será usar la funcion find con el primer parámetro list para que lo devuelva formateado con el identificador de cada opcion como key de los nodos del array
        $subcategorias = $this->ArticuloSubcategoria->find('list',array('conditions' => array('ArticuloSubcategoria.categoria_id' => $id), 'fields' => 'nombre_subcategoria'));
        $this->set('listado_subcategorias',$subcategorias);
    }

}
?>

5.- RENDERING THE SELECT OPTION AT THE VISTA

<? echo $form->input('Articulo.id_subcategoria', array('options' => $listado_subcategorias,'label'=>false,'div'=>null));?>

I hope I helped you:

Complete Guide

Ajax Plugin for CakePhp

    
answered by 02.05.2018 в 19:37