简体   繁体   中英

Example of calling CakePHP function from jQuery

I am new to CakePHP and I am trying to figure you how to make an asynchronous call from a CakePHP view to a function in the controller. I would like the controller function to return a string and have the view display this string. I would also like to to do this without using helpers. I have been trying to find examples on the web but have been unable to do so. Does anyone have a simple example? I am also using jQuery.

Thanks

CakePHP has a built-in JS Helper to help write aJax functions. The only catch is to include jquery in your head or cake will throw jQuery errors. Heres more information http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html

Your Form:

<?php 
  echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
  echo $this->Form->input('username');
  echo $this->Form->submit('Check Username');
  echo $this->Form->end();
?>

The Ajax Function: ('update'=>'#na') is the id of the element you want to update in your view.

<?php
  $data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
  $this->Js->get('#YourForm')->event(
    'submit',
    $this->Js->request(
      array('action' => 'checkUsername', 'controller' => 'user'),
      array(
        'update' => '#na',
        'data' => $data,
        'async' => true,    
        'dataExpression'=>true,
        'method' => 'POST'
      )
    )
  );
  echo $this->Js->writeBuffer();                                                 
?>

The Function in User Controller

function checkUsername(){
  $this->autoRender = false;

  $username = $this->User->find('first', array('conditions'=>array('User.username'=>$this->request->data['User']['username'])));

  if ( $username == true ) 
    echo 'Username is taken';
  else
    echo 'Username is not taken';  
}

EDIT* * * If you want to use jQuery to do this and not the CakePHP Helper you can use aJax to call an action, then update your element like below *

$('#element').on('click', function() {
  $.ajax({
      url : '/controller/action',
      type: 'POST',
      success : function(response){
        $('#elementToUpdate').html(response);
      }
  });

} });

In your Controller Action you can return the "string" you would like to show in the view

function action(){
  $string = 'Show this in the view';

   return $string;
}

The above example would be executed when you "Click" an element with an id of "element" then upon "Success" would change element with id of "elementToUpdate" to the String "Show this in the view" Since it was returned from the controller action.

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