简体   繁体   中英

Ajax in Cakephp 2.x

I have a problem, i need to use, ajax in a form, in my page i have to change the color of a label after i search if a data is in a data base, if the data exist i must change the color of the label to red, if not i have to changed to green, i know how to use this in pure php, but i don´t know how to do that in cakephp, if i am not wrong in pure php this is the forme to do it:

View

<form action="prueba.php" method="post">
<input type="text" id="txt_prueba" class="validador" />
<submit value="enviar"/>
</form>

View in Cake

<?php
  echo $this->Form->create('Prueba', array('url' => 'prueba.php', 'type' => 'post'));

         echo $this->Form->input('textoPrueba', array('label' => false,
            'class' => 'validador'));
   echo $this->Form->end(); ?>

Script

    $(".validador").on('keyup keypress blur change', function (tecla) {
      $.ajax({
          method: "POST",
          url: "algun.php",
          data: { 
           name: $("#txt_prueba").val();
          }
      })
      .done(function( msg ) {
           if (msg=="Yes"){
                  $("#txt_prueba").css('background-color', 'red');
            } else{
                  $("#txt_prueba").css('background-color', 'green');
            }
       });
});

Controller

require('conexion.php');

$consulta = $_POST['name'];

if (isset($consulta)) {

    $consulta = mysqli_query($conexion, "SELECT * FROM tabla1
    WHERE nombre LIKE '$consulta'");

   $filas = mysqli_num_rows($consulta);

   if ($filas === 0) {
            echo 'Not';

   }else {
     echo 'Yes';
   }
};

Have you read something about CakePHP? You should read some basic tutorial

  1. Download and install CakePHP ( https://book.cakephp.org/3.0/en/installation.html )
  2. Build Your first controller with action and view ( https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/articles-controller.html )
  3. Add Your JavaScript AJAX code in default.ctp layout file
  4. Build Your first form ( https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/articles-controller.html#create-add-template )
  5. Run, if You have some problems, try find solution on stackoverflow.com...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM