A. K. M. Tariqul Islam
A. K. M. Tariqul Islam

Reputation: 2834

CakePHP AJAX call

I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:

//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 this isn't working. Anybody know why or how to modify it so that it works?

Upvotes: 4

Views: 10813

Answers (3)

Brett Stewart
Brett Stewart

Reputation: 478

CakePHP has a JS Helper to help write aJax functions. The only catch is to include jquery in your head our cake will throw jQuery errors.

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:

<?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;
  //run your query here 

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

Upvotes: 2

Cool Brain
Cool Brain

Reputation: 48

There are many examples through google. Here is a good one to visit.

Upvotes: 1

Andrew Bashtannik
Andrew Bashtannik

Reputation: 972

It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.

This method is recommended for your needs, but not obligated, of course.

Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:

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

Also, try not to use such code construction in the future.

Upvotes: 5

Related Questions