CakePHP AJAX Call

I use CakePHP, and this is my first project in this structure. I am going to send an input value to an action UsersController check_username(). And fill in the element having id nawith the string returned check_username(). So far I have done:

//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>

//after the form
<script type="text/javascript">
    function check_username(un) {
        $.ajax({
            type: 'POST',
            url: '/oes/users/check_username',
            data: {username:un},
            cache: false,
            dataType: 'HTML',
            beforeSend: function(){
                $('#na').html('Checking...');
            },
            success: function (html){
                $('#na').val(html);
            }
        });
    }
</script>

//and my check_username() is
public  function check_username(){
    return 'Test string';
}

But that does not work. Does anyone know why and how to modify it to make it work?

+4
source share
3 answers

check_username. CakePHP- JsonView XHR (. http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). .json(:/oes/users/check_username.json) JSON JSON.

, , .

, CakePHP check_username, , . - :

public function check_username(){
     $this->autoRender = false;
     echo 'Test string';
}

, โ€‹โ€‹ .

+5

CakePHP JS, aJax. , jquery , jQuery.

:

<?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();
?>

Ajax:

<?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();                                                 
?>

function checkUsername(){
  $this->autoRender = false;
  //run your query here 

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

Google has a lot of examples. Here is a good place to visit.

+1
source

All Articles